Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join iterator of &str [duplicate]

Tags:

iterator

rust

What is the canonical method to convert an Iterator<&str> to a String, interspersed with some constant string (e.g. "\n")?

For instance, given:

let xs = vec!["first", "second", "third"];
let it = xs.iter();

There is a way to produce a string s by collecting into some Iterable and joining the result:

let s = it
    .map(|&x| x)
    .collect::<Vec<&str>>()
    .join("\n");

However, this unnecessarily allocates memory for a Vec<&str>. Is there a more direct method?

like image 760
Mateen Ulhaq Avatar asked May 08 '19 03:05

Mateen Ulhaq


People also ask

What does collect () do in Rust?

collect() can take all the values in an Iterator 's stream and stick them into a Vec . And the map method is now generating Result<i32, &str> values, so everything lines up.

What is iterator in Rust?

Iterators. An iterator helps to iterate over a collection of values such as arrays, vectors, maps, etc. Iterators implement the Iterator trait that is defined in the Rust standard library. The iter() method returns an iterator object of the collection. Values in an iterator object are called items.

How do you know if an iterator is empty in Rust?

You can make your iterator peekable and peek the first item; if it's None , then the iterator is empty. peek doesn't consume the item1, so the next call to next will return it.


1 Answers

You could use the itertools crate for that. I use the intersperse helper in the example, it is pretty much the join equivalent for iterators.

cloned() is needed to convert &&str items to &str items, it is not doing any allocations. It can be eventually replaced by copied() when [email protected] gets a stable release.

use itertools::Itertools; // 0.8.0

fn main() {
    let words = ["alpha", "beta", "gamma"];
    let merged: String = words.iter().cloned().intersperse(", ").collect();
    assert_eq!(merged, "alpha, beta, gamma");
}

Playground

like image 101
chpio Avatar answered Oct 02 '22 23:10

chpio