CodeBlanks Logo Icon CodeBlanks

What is ownership?

Learn what the ownership rules do for you.

What is ownership?

Ownership is Rust's memory management model and rests on three rules:

  • Every value has an owner (a variable).
  • There can be only one owner at a time.
  • When the owner goes out of scope, the value is dropped automatically (drop).
{
    let s = String::from("merhaba");  // s is the owner
    println!("{s}");
}   // scope ends: s is dropped, memory freed

There is no garbage collector and no manual free; the compiler inserts the drop point itself.

The Drop trait

By implementing Drop for a type, you can see what happens when it is dropped; cleanups such as closing files and releasing locks become automatic this way:

struct Kaynak(&'static str);

impl Drop for Kaynak {
    fn drop(&mut self) {
        println!("{} bırakıldı", self.0);
    }
}

let _a = Kaynak("a");
let _b = Kaynak("b");
// end of scope: b is dropped first, then a (reverse order)

Practice Drop order

Write the Kaynak type above and its Drop implementation. In main, declare let _a = Kaynak("a"); and let _b = Kaynak("b");, and print println!("main bitiyor");.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
struct Kaynak(&'static str);

impl Drop for Kaynak {
    fn drop(&mut self) {
        println!("{} bırakıldı", self.0);
    }
}

fn main() {
    let _a = Kaynak("a");
    let _b = Kaynak("b");
    println!("main bitiyor");
}

Expected output

main bitiyor
b bırakıldı
a bırakıldı

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is a <code>String</code>'s memory freed?

  • When the program ends
  • When the GC runs
  • When free is called
  • When its owner goes out of scope Correct answer

Explanation: At the end of the scope the compiler adds the drop call automatically; it is Rust's counterpart to C++'s RAII idea.

2 Cleanup method

Question
impl Drop for Dosya {
    fn ____(&mut self) {
        println!("kapatıldı");
    }
}
Answer
impl Drop for Dosya {
    fn drop(&mut self) {
        println!("kapatıldı");
    }
}

Explanation: The Drop trait's only method is drop, called at the end of the scope.

3 Rule

Term Meaning
One owner For every value
Kapsam sonu Automatic drop
Drop trait Custom cleanup
Reverse order Last declared is dropped first

All lessons in Beginner