Is there a difference between these for loops?

fn main() {
    let conversation = vec!["hello","bye","why go so fast", "i dont like u", "----"];
    for word in &conversation {
        println!("{}",word);
    }
    for word in conversation.iter() {
        println!("{}",word);
    }
}


(Playground)

Output:

hello
bye
why go so fast
i dont like u
----
hello
bye
why go so fast
i dont like u
----

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.10s
     Running `target/debug/playground`

There's no difference in functionality/behavior. Generally, explicit for … in collection.iter() is considered unnecessary, since the shorter alternative also works just fine.

for loops use IntoIterator, and if you look up what that does for &Vec<T> you'll see they're identical.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.