Why endless iterator when using chars().next()?

Why does this produce an endless iterator over just the first char in the str?

fn main() {
    let name = "string".to_string();
    let n = name.as_str();
    while let Some(item) = n.chars().next() {
        println!("{}", item)
    }
}

(Playground)

I would have expected next() to actually move onto the next char, but it never does.

replacing with a simple 'for c in n.chars()" solves the issue

n.chars().next() means "make a fresh iterator from n, then take its first char". What you wanted is expressed like this:

fn main() {
    let name = "string".to_string();
    let n = name.as_str();
    // Explicitly create the iterator once...
    let mut n = n.chars();
    // ...then iterate over it in a loop
    while let Some(item) = n.next() {
        println!("{}", item)
    }
}
2 Likes

Oh that makes sense! Thank you!

Also note that even after applying @Cerber-Ursi's solution, you are still manually implementing for loop. The most idiomatic way would be to use it directly:

fn main() {
    let name = "string".to_string();
    for c in name.chars() {
        println!("{}", c)
    }
}

You can read documentation for the for keyword, which explains what the syntactic sugar expands to. It is slightly more verbose than what you have wrote, because while loop is also a syntactic sugar. But it boils down to the same concept. Create an iterator and poll it until it stops yielding items.

1 Like