kob003
kob003

Reputation: 3727

iterating through the chars on the reference of a string

This does not work:

let mut word = String::from("kobin");
for x in &word.chars() {
    println!("looping through word: {}", x);
}

But this works:

let mut word = String::from("kobin");
let word_ref = &word;
for x in word_ref.chars() {
    println!("looping through word: {}", x);
}

whats the difference. Aren't both referencing to the word?

Upvotes: 0

Views: 165

Answers (1)

Silvio Mayolo
Silvio Mayolo

Reputation: 70267

&word.chars() is the same as &(word.chars()), so you're taking the iterator and borrowing it. Rust points out in this case that a reference to Chars (the iterator type) is not an iterator, but a Chars itself is. Parenthesizing fully will work

for x in (&word).chars() { ... }

But when calling methods on things, Rust is smart and will automatically borrow, so you can simply do

for x in word.chars() { ... }

and Rust is smart enough to know that str::chars only needs &self and will insert the & for you.

Upvotes: 3

Related Questions