Day5:for .. in & iter - 100DayOfRust
BC
Posted on November 15, 2019
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);
}
}
Result:
i is 1
i is 2
i is 3
i is 4
=====
Alice
Bob
Chris
=====
Jack
Jack
Jack
=====
Jack
Jack
Jack
💖 💪 🙅 🚩
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.