Lesson 2 · Unit 03
Ownership
Who owns a value, when it moves, and how to lend it
What you practise
Stringagainst&str, a value has one owner, moving and the use after a move,clone, lending with&, values dropped at the end of their scope
Try a question from this lesson
Pick one
Braces make a block. A variable lives until the } of the block it was made in. Which line does the compiler refuse?
let a = 1;
{
let b = 2;
println!("{}", a + b);
}
println!("{}", a + b);Correct answer
Line 6
Why
b is made inside the inner braces and is gone at their }. Line 4 is inside, so it may use both names. Line 6 is outside: the compiler says it cannot find b in this scope.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Scope
The scope of a variable is the part of the program where its name can be used: from its let to the closing brace of its block.
At that brace the value is dropped: Rust throws it away and frees the memory it used, at once, with no work from you.
{
let note = 7; // note starts here
println!("{note}");
} // note is dropped
println!("after");Concept
Two kinds of text
Text written in the code, like "Ada", is fixed. Its type is &str.
A String is text your program owns and can grow. String::from("Ada") makes one.
A dot calls a function that belongs to a value: name.push_str("!") adds text to the end of name.
let fixed = "Ada";
let mut name = String::from("Ada");
name.push_str(" Lovelace");
println!("{fixed} / {name}");Concept
One owner
Every value has exactly one owner: the variable that holds it. When the owner's scope ends, the value is dropped.
Giving a String to another variable moves it. The old name can no longer be used, so the text is never dropped twice.
Numbers, bool and char are tiny. They are copied instead, and both names stay usable.
let a = 5;
let b = a; // a number is copied
println!("{a} {b}");
let s = String::from("hi");
let t = s; // text is moved
println!("{t}");9 more exercises in the app
- 2× true or false
- 2× type the answer
- 3× multiple choice
- 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.