JavaScript Do… something Python Something… slightly different Rust? Detect problem when compiling Iterator invalidation: modify while iterating ==> Runtime Error
1. Every value is owned by a single variable. owns moved ~~~~~~~~~~~~~~~~ (a) Owner gets to decide whether it is mutable. ✅ ❌ ❌ “moved” ~~~~~~~~~~~~~~~~ fn example() { let mut shelf = Vec::new(); shelf.push(…); let shelf2 = shelf; shelf.push(…); print(shelf2.len()); shelf2.push(…); }
borrowed here book ~~~~~~~~~~~~~~~~ 2. Shared borrows make the value temporarily immutable. fn example() { let mut shelf = Vec::new(); shelf.push(…); for book in &shelf { read(book); shelf.push(…); } shelf.push(…); } ❌ “immutable while borrowed” ✅
`shelf` mutably borrowed here book ~~~~~~~~~~~~~~~~~~~~~ 3. Mutable borrows have unique access to the value. borrows mutably ❌ ✅ ✅ make changes fn example() { let mut shelf = Vec::new(); shelf.push(…); for book in &mut shelf { edit(book); print(shelf.len()); } shelf.push(…); }
Image::load(path) }) .collect() } For each path… …load an image… …create and return a vector. paths = [ “a.jpg”, “b.png”, …, “c.jpg” ] borrowed from caller
= 0; paths.par_iter() .map(|path| { if path.ends_with(“.jpg”) { jpgs += 1; } Image::load(path) }) .collect() } How many jpgs seen so far? …add 1 to the counter. If current file name ends in “jpg”… 0 0 + 1 0 + 1 1 1 1