DEV Community

BC
BC

Posted on

Day5:for .. in & iter - 100DayOfRust

for .. in

fn main() {
    for i in 1..5 {
        println!("i is {}", i);
    }

    let mut names = vec!["Alice", "Bob", "Chris"];
    // iter() will borrow element in the array
    // elements can be reused after loop
    println!("{}", "=".repeat(5));
    for name in names.iter() {
        println!("{}", name);
    }

    // Borrow as mutably
    // unless change names to be `let mut names =`
    println!("{}", "=".repeat(5));
    for name in names.iter_mut() {
        *name = "Jack";
        println!("{}", name);
    }

    // this equals to names.into_iter()
    // into_iter will move ownership
    // so after this, we cannot use elements in names any more
    println!("{}", "=".repeat(5));
    for name in names {
        println!("{}", name);
    }
}
Enter fullscreen mode Exit fullscreen mode

Result:

i is 1
i is 2
i is 3
i is 4
=====
Alice
Bob
Chris
=====
Jack
Jack
Jack
=====
Jack
Jack
Jack
Enter fullscreen mode Exit fullscreen mode

Top comments (0)