Lesson 2 · Unit 01
Ownership and moves
One owner per value, and assignment hands it over
What you practise
- A value is dropped when its owner goes out of scope, assignment moves,
Copytypes,clone, passing to a function gives it away
Try a question from this lesson
Pick one
In Python, t = s gives one string two names. Which line does the Rust compiler reject?
let s = String::from("hi");
let t = s;
println!("{t}");
println!("{s}");Correct answer
Line 4
Why
let t = s; moves the string: t owns it now and s can no longer be used. Python has nothing like this. One owner means the memory is freed exactly once, with no garbage collector.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Ownership
Every value has exactly one owner, a variable. When the owner goes out of scope the value is dropped and its memory is freed.
Assigning a String or a Vec to another variable moves it: the new variable is the owner and the old name is dead. The compiler tracks this. Nothing is checked at run time.
let a = vec![1, 2, 3];
let b = a;
println!("{}", b.len());11 more exercises in the app
- 5× multiple choice
- 3× type the answer
- 1× 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.