← Вернуться к курсу: Rust from scratch

Ownership and move

Видео скоро появится

Ownership is the most characteristic idea of Rust and the one that explains how it manages memory without a garbage collector and without you freeing it by hand. It is hard at first, because it goes against what other languages do, but the rules are few and the compiler helps you with very clear messages. If you understand this lesson, the rest of the language fits much better. Take your time and run every example.

Stack and heap

The stack stores values of known, fixed size, like integers or bool; entering and leaving is very fast. The heap stores data whose size can change or is unknown at compile time, like the text of a String; reserving memory there is slower and it must be given back. A String has a part on the stack (pointer, length, capacity) and its content on the heap. The key question is: who is in charge of freeing that content, and when? Rust answers with the ownership rules.

  • Each value has a single owner (a variable).
  • There can be only one owner at a time.
  • When the owner goes out of scope (reaches the closing brace), the value is freed automatically.

Move: moving instead of copying

With integers, let b = a copies the number and both variables remain valid, because copying an i32 is very cheap. With a String, let b = a does not copy the heap text: it moves ownership. After the assignment, a is no longer valid and the compiler will stop you from using it. This way there are never two owners trying to free the same memory (the famous double free in C). If you really want two independent copies, ask for it with clone(), which also duplicates the heap data.

rust
fn main() {
    let x = 5;
    let y = x;               // i32 is Copy: both are valid
    println!("{x} {y}");

    let s1 = String::from("hello");
    let s2 = s1.clone();     // deep copy of the heap data
    println!("{s1} {s2}");

    let s3 = String::from("moved");
    let s4 = s3;             // ownership moves to s4
    println!("{s4}");
    // println!("{s3}");     // would fail: s3 was moved
}

The following program does NOT compile on purpose; it is the error you will see again and again when starting. The compiler says "borrow of moved value: s1" and points to exactly where the value was moved. The fix depends on what you want: use clone, use a reference (next lesson) or just do not use the original variable.

rust
// Does NOT compile on purpose: use after move
fn main() {
    let s1 = String::from("hello");
    let s2 = s1;
    println!("{s1}, {s2}");
}

Ownership and functions

Passing a value to a function works the same as assigning it: it moves ownership (or copies, if the type is Copy). Simple types such as integers, floats, bool, char and tuples of them implement Copy. A String, a Vec or anything living on the heap does not. A function can return the value to hand ownership back, but doing that all the time would be annoying; that is why references exist, which we will see in the next lesson. When the function ends, the values it owns are freed.

rust
fn consume(text: String) {
    println!("consuming: {text}");
} // text is dropped here

fn double(n: i32) -> i32 {
    n * 2
}

fn add_world(mut text: String) -> String {
    text.push_str(" world");
    text // give ownership back
}

fn main() {
    let a = 4;
    println!("{} {}", double(a), a); // a still usable (Copy)

    let greeting = String::from("hello");
    let greeting = add_world(greeting); // moved in, moved out
    println!("{greeting}");

    consume(greeting);
    // greeting is no longer valid here
}

Проверьте себя

Вопрос 1 из 4

What happens with let s2 = s1; if s1 is a String?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →