Day5:for .. in & iter - 100DayOfRust

bitecode

BC

Posted on November 15, 2019

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
💖 💪 🙅 🚩
bitecode
BC

Posted on November 15, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

December Surely Looks Busy!
opensource December Surely Looks Busy!

November 29, 2024

December Surely Looks Busy!
opensource December Surely Looks Busy!

November 29, 2024

Daemons on macOS with Rust
undefined Daemons on macOS with Rust

November 29, 2024