Lesson 1 · Unit 04
Collections and iterators
Loops that own or borrow, closures and lazy pipelines
What you practise
VecandHashMap, closures,map,filterandcollect, laziness, ownership inside a loop
Try a question from this lesson
Pick one
In Python a list is untouched by a for loop over it. Which line does the Rust compiler reject?
let names = vec![
String::from("ana"),
String::from("bo"),
];
for n in names {
println!("{n}");
}
println!("{}", names.len());Hint
Each n is a String, not a reference. Where did it come from?
Correct answer
Line 8
Why
for n in names takes ownership of the vector and moves each string into n. Afterwards names is gone: "borrow of moved value". Writing for n in &names borrows instead and keeps the vector.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Three ways to loop
for x in v consumes the collection: each item moves into x.
for x in &v borrows it: x is a reference to each item.
for x in &mut v borrows it mutably: *x changes the item in place.
These are the same three choices as self, &self and &mut self.
let mut v = vec![1, 2, 3];
for x in &mut v {
*x += 1;
}
for x in &v {
print!("{x} ");
}
println!("{}", v.len());Concept
Iterators are lazy
v.iter() gives an iterator over references to the items. Adapters such as map and filter wrap it in a new iterator and do no work yet, like a Python generator.
A consumer such as collect, sum or a for loop pulls the items through the whole chain, one at a time. The chain compiles to the same code as a hand-written loop.
let v = vec![1, 2, 3];
let doubled = v.iter().map(|x| x * 2);
let out: Vec<i32> = doubled.collect();
println!("{:?}", out);10 more exercises in the app
- 5× type the answer
- 2× multiple choice
- 1× fill the blanks
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.