Map char chunks

Hi,

I am a new rust user and I am struggling to figure out the chunk map syntax:

use itertools::Itertools;
fn main(){
println!(
        "{}",
        "hello world"
            .chars()
            .chunks(2)
            .map(|c| String::from(c))
            .join("\n")
    );
}

I want to take “hello world” and print each two consecutive characters on a new line.

The compilation fails with:

--> src/main.rs:55:14
   |
55 |             .map(|c| String::from(c))
   |              ^^^
   |
   = note: the method `map` exists but the following trait bounds were not satisfied:
           `&mut itertools::IntoChunks<std::str::Chars<'_>> : std::iter::Iterator`

How do I read this error message?

The error message is saying that IntoChunks is not an Iterator. Sometimes it could be because your type parameter doesn’t meet some constraint, but in this case it’s universal. The docs say:

IntoChunks is based on GroupBy : it is iterable (implements IntoIterator , not Iterator ), and it only buffers if several chunk iterators are alive at the same time.

This is a matter of getting the ownership and lifetimes right, but you can call .into_iter() to iterate from there.

Then you’ll find that String::from(c) doesn’t work with the Chunk items. That type is an Iterator though, so you could collect() or use String::from_iter(c). Or even fancier, use c.format("") to create a dynamic Format item which will be displayed by the join("\n").

use itertools::Itertools;
fn main() {
    println!(
        "{}",
        "hello world"
            .chars()
            .chunks(2)
            .into_iter()
            .map(|c| c.format(""))
            .join("\n")
    );
}
1 Like

Thank you!
That explains it really well.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.