Boss lesson · Unit 01
Borrowing
Lend a value instead of giving it away
What you practise
&and&mut, many readers or one writer, a reference cannot outlive its value,Stringagainst&str, slices- Compiler errors read and fixed
Try a question from this lesson
Pick one
This function takes ownership, so name is gone after one call. Which parameter lets the caller keep its string?
fn len_of(s: String) -> usize {
s.len()
}
let name = String::from("ferris");
let n = len_of(name);Correct answer
s: &String
Why
&String is a reference: the function may look at the string but does not own it, so nothing is moved and nothing is dropped when the function returns. This is called borrowing.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Borrowing
&x makes a reference to x without taking ownership. Whoever holds it borrows the value, and the owner still owns it afterwards.
Python names are all shared references that a garbage collector tracks. Rust references are checked by the compiler instead: one can never outlive the value it points to.
let s = String::from("hi");
let r1 = &s;
let r2 = &s;
println!("{r1} {r2} {s}");Concept
Many readers or one writer
At any moment a value can have any number of & references, or exactly one &mut reference. Never both.
A writer could move or free what a reader is looking at. Banning the overlap rules out that whole class of bug at compile time, before threads even enter the picture.
let mut s = String::from("hi");
let w = &mut s;
w.push('!');
let r = &s;
println!("{r}");10 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 2× fill the blanks
- 1× true or false
- 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.