CodeBlanks Logo Icon CodeBlanks

Summary - Ownership

Combine move, Copy and function calls to trace ownership flow.

Ownership summary

Three rules: every value has a single owner; when the owner leaves scope the value is dropped; assignment and function calls move non-Copy values. Copy types (numbers, bool, char, tuples/arrays with Copy fields) are copied. A deep copy is made explicitly with .clone(). Returning transfers ownership to the caller. These rules provide memory safety without a garbage collector.

Thinking in scopes

To see when a value is dropped, look at the curly braces: a value is dropped at the end of the block where its owner was declared. To drop a value earlier you can call drop(value); this is especially useful for releasing locks and large buffers early.

let buyuk = vec![0u8; 10_000_000];
// ... use it ...
drop(buyuk);         // memory freed here
// buyuk can no longer be used

Practice Ownership chain

Let fn yeni_veri() -> String return "veri" and fn tuket(s: String) -> usize return its length. In main, do let s = yeni_veri();, let kopya = s.clone();, let n = tuket(s); and print kopya and n.

Starter code

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

Sample solution

main.rs
fn yeni_veri() -> String {
    String::from("veri")
}

fn tuket(s: String) -> usize {
    s.len()
}

fn main() {
    let s = yeni_veri();
    let kopya = s.clone();
    let n = tuket(s);
    println!("{} {}", kopya, n);
}

Expected output

veri 4

Questions and answers

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

1 Which of these compiles?

  • let v = vec![1]; let w = v; v.len();
  • None
  • let a = 5; let b = a; println!("{a}"); Correct answer
  • let a = String::new(); let b = a; println!("{a}");

Explanation: Because i32 is Copy, a stays valid; String and Vec are moved, so the other two give E0382.

2 Drop early

Question
let tampon = vec![0u8; 1024];
____(tampon);
Answer
let tampon = vec![0u8; 1024];
drop(tampon);

Explanation: drop releases the value immediately; the variable can't be used afterwards.

3 Group summary

Term Meaning
Sahip Single
Move Non-Copy types
Copy Copy types
clone Explicit deep copy

All lessons in Beginner