Search⌘ K

Iterating on Strings

Explore the unique ways Rust handles iteration over strings and string slices. Learn to use the chars() and bytes() methods to iterate over characters and bytes, including special Unicode symbols. Understand common iteration errors and how to resolve them.

We'll cover the following...

Strings and string slices behave a bit strangely with iteration as well. Let’s have a look at why:

Rust 1.40.0
fn main() {
let name = "Michael";
for x in name {
println!("{}", x);
}
}

This results in the error message:

error[E0277]: `&str` is not an iterator
 --> src/main.rs:4:14
  |
4 |     for
...