Bitpath

Lesson 2 · Unit 03

Ownership

Who owns a value, when it moves, and how to lend it

13 exercisesabout 3 min

What you practise

  • String against &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?

Rust
let a = 1;
{
    let b = 2;
    println!("{}", a + b);
}
println!("{}", a + b);

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.

Rust
{
    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.

Rust
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.

Rust
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.

One email when Bitpath is ready to try. Nothing else. Privacy