Lesson 1 · Unit 04
Vectors and borrowing
A list of values, safe lookups, and many readers or one writer
What you practise
Vec,push, indexing againstget, looping by reference, slices, many readers or one writer
Try a question from this lesson
Pick one
vec! makes a list of values: a vector. Square brackets pick one by position, and positions start at 0. What prints?
let scores = vec![70, 85, 90];
println!("{}", scores[0]);Correct answer
70
Why
Position 0 is the first item, so scores[0] is 70. The second item is at position 1 and the third at position 2. Counting from 0 feels odd for a week and natural ever after.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Vectors
A vector, Vec, holds many values of one type, in order. A position is called an index, and indexes start at 0.
len() gives the number of items. push adds one at the end, so the vector needs mut.
{:?} in a gap prints a whole collection, for you to inspect.
let mut scores = vec![70, 85];
scores.push(90);
println!("{}", scores.len());
println!("{:?}", scores);Concept
Asking politely: `get`
v.get(i) never stops the program. Its answer is one of two things: Some(value) when there is an item at that index, or None when there is not.
A match handles both. In the first arm, n becomes the item that was found.
let v = vec![10, 20, 30];
match v.get(3) {
Some(n) => println!("found {n}"),
None => println!("nothing there"),
}Concept
Many readers or one writer
A loan made with & is for reading. Any number of them may exist at once.
Changing a value needs it to yourself: while a reading loan is still in use, nobody may change the value.
A loan ends at its last use. Below, first is finished before the push, so all is well.
let mut v = vec![1, 2, 3];
let first = &v[0]; // a reader
println!("{first}"); // its last use
v.push(4); // writing is fine now
println!("{:?}", v);9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× true or false
- 2× fill the blanks
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.