Skip to content

Iterator::intersperse doesn't seem to work correctly when collecting into a StringΒ #81145

Closed
@PatchMixolydic

Description

@PatchMixolydic

I tried this code (playground):

#![feature(iter_intersperse)]

fn main() {
    let contents = vec![1, 2, 3];

    let contents_string = contents
        .into_iter()
        .map(|id| id.to_string())
        .intersperse(", ".to_owned())
        .collect::<String>();

    println!("{}", contents_string);
}

I expected to see this happen: ", " is placed between each digit:

1, 2, 3

Instead, this happened: intersperse does not insert ", " between "1" and "2":

12, 3

Note that this works as expected when collecting into a Vec (playground):

#![feature(iter_intersperse)]

fn main() {
    let contents = vec![1, 2, 3];

    let contents_strings = contents
        .into_iter()
        .map(|id| id.to_string())
        .intersperse(", ".to_owned())
        .collect::<Vec<_>>();

    println!("{:?}", contents_strings);
}
["1", ", ", "2", ", ", "3"]

Meta

rustc --version --verbose:

rustc 1.51.0-nightly (8a6518427 2021-01-16)
binary: rustc
commit-hash: 8a6518427e11e6dd13d6f39663b82eb4f810ca05
commit-date: 2021-01-16
host: x86_64-unknown-linux-gnu
release: 1.51.0-nightly
LLVM version: 11.0.1

@rustbot modify labels: +A-iterators +T-libs

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-iteratorsArea: IteratorsC-bugCategory: This is a bug.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions