I'm confused how a mutable reference works in a for-loop while an immutable reference does not. Is it an iterator?
I found that after loop, the reference chars refers to value "".
No reference
fn main() {
let str_value: String = "abc".to_string();
let chars = str_value.chars();
for char_value in chars {
println!("char: {}", char_value);
}
}
char: a
char: b
char: c
Immutable reference
fn main() {
let str_value: String = "abc".to_string();
let chars = str_value.chars();
for char_value in &chars {
println!("char: {}", char_value);
}
}
error[E0277]: `&std::str::Chars<'_>` is not an iterator
--> src/main.rs:5:23
|
5 | for char_value in &chars {
| -^^^^^
| |
| `&std::str::Chars<'_>` is not an iterator
| help: consider removing the leading `&`-reference
|
= help: the trait `std::iter::Iterator` is not implemented for `&std::str::Chars<'_>`
= note: `std::iter::Iterator` is implemented for `&mut std::str::Chars<'_>`, but not for `&std::str::Chars<'_>`
= note: required by `std::iter::IntoIterator::into_iter`
Mutable reference
fn main() {
let str_value: String = "abc".to_string();
let mut chars = str_value.chars();
for char_value in &mut chars {
println!("char: {}", char_value);
}
// why chars equal ""?
assert_eq!(chars.as_str(), "");
}
char: a
char: b
char: c
std::iter::Iteratoris implemented for&mut std::str::Chars<'_>, but not for&std::str::Chars<'_>", so&mut charsis indeed an iterator.