Bird
Raised Fist0
Rustprogramming~10 mins

Ownership and functions in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Ownership and functions
Function called with ownership
↓
Ownership moves to function parameter
↓
Function uses the value
↓
Function ends
↓
Ownership dropped if not returned
↓
Caller cannot use value unless ownership returned
When a function takes ownership of a value, the ownership moves into the function. After the function ends, if ownership is not returned, the caller loses access.
Execution Sample
Rust
fn take_ownership(s: String) {
    println!("Inside function: {}", s);
}

fn main() {
    let s = String::from("hello");
    take_ownership(s);
    // println!("Outside function: {}", s); // error
}
This code shows a function taking ownership of a String, printing it, and then the caller losing access to it.
Execution Table
StepActionVariable 's' StateOwnershipOutput/Result
1Create String 'hello's = "hello"Owned by mainNo output
2Call take_ownership(s)s moved to function parameterOwned by take_ownershipNo output yet
3Inside take_ownership: print ss = "hello"Owned by take_ownershipPrint: Inside function: hello
4Function ends, s droppeds droppedOwnership lostNo output
5Back in main, try to use ss no longer validNo ownershipError if uncommented: use of moved value
💡 Execution stops because ownership of 's' moved to function and was dropped; main cannot use 's' after.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
s"hello"moved to functiondroppedinvalid
Key Moments - 2 Insights
Why can't we use 's' in main after calling take_ownership?
Because ownership of 's' moved into the function (see execution_table step 2), and after the function ends, 's' is dropped (step 4), so main no longer owns or can use it.
What happens to the value inside 's' when the function ends?
The value is dropped and memory freed because the function had ownership and did not return it (execution_table step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step does ownership of 's' move from main to the function?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Check the 'Ownership' column in execution_table row for step 2.
According to variable_tracker, what is the state of 's' after step 4?
AStill owned by main
BDropped and invalid
CMoved to function but still valid
DReturned to main
💡 Hint
Look at the 'After Step 4' and 'Final' columns for 's' in variable_tracker.
If the function returned 's' back, how would the ownership change after step 4?
AOwnership moves back to main
BOwnership stays with function
COwnership is lost permanently
DOwnership moves to a new variable
💡 Hint
Think about ownership rules and returning values from functions.
Concept Snapshot
Ownership and functions in Rust:
- Passing a value to a function moves ownership.
- Function parameter owns the value inside the function.
- When function ends, value is dropped unless returned.
- Caller loses access unless ownership is returned.
- Prevents double free and dangling pointers.
Full Transcript
This visual trace shows how ownership moves when a function takes a parameter in Rust. Initially, main owns the String 's'. When calling take_ownership(s), ownership moves to the function parameter. Inside the function, 's' is valid and printed. After the function ends, 's' is dropped because the function owns it and does not return it. Back in main, 's' is invalid and cannot be used. This prevents errors from using freed memory. The key idea is ownership moves into functions and is dropped unless returned.

Practice

(1/5)
1. What happens when a function in Rust takes ownership of a variable passed to it?
easy
A. The variable is shared between the function and the caller simultaneously.
B. The variable is copied and both original and function have ownership.
C. The function borrows the variable temporarily without taking ownership.
D. The original variable can no longer be used after the function call.

Solution

  1. Step 1: Understand ownership transfer in Rust functions

    When a function takes ownership, it means the variable's ownership moves to the function.
  2. Step 2: Effect on original variable after function call

    Since ownership moved, the original variable cannot be used anymore after the call.
  3. Final Answer:

    The original variable can no longer be used after the function call. -> Option D
  4. Quick Check:

    Ownership transfer = original variable unusable [OK]
Hint: Ownership moves to function, original variable becomes invalid [OK]
Common Mistakes:
  • Thinking ownership is shared, not moved
  • Assuming variable is copied automatically
  • Confusing borrowing with ownership transfer
2. Which of the following function signatures correctly borrows a string slice without taking ownership?
easy
A. fn print_name(name: String) { println!("{}", name); }
B. fn print_name(name: &String) { println!("{}", name); }
C. fn print_name(name: &str) { println!("{}", name); }
D. fn print_name(name: String) -> String { name }

Solution

  1. Step 1: Identify borrowing syntax for string slices

    Borrowing a string slice uses &str type, which is a reference to a string slice.
  2. Step 2: Check each signature for borrowing without ownership

    fn print_name(name: &str) { println!("{}", name); } uses &str, which borrows without taking ownership. fn print_name(name: &String) { println!("{}", name); } borrows a String reference but &str is more idiomatic for slices.
  3. Final Answer:

    fn print_name(name: &str) { println!("{}", name); } -> Option C
  4. Quick Check:

    Borrow string slice = &str parameter [OK]
Hint: Use &str to borrow string slices without ownership [OK]
Common Mistakes:
  • Using String parameter takes ownership
  • Confusing &String with &str
  • Returning ownership when not needed
3. What will be the output of this Rust code?
fn take_ownership(s: String) {
    println!("Inside function: {}", s);
}

fn main() {
    let s = String::from("hello");
    take_ownership(s);
    println!("Outside function: {}", s);
}
medium
A. Inside function: hello Compile error: use of moved value 's'
B. Inside function: hello Outside function: hello
C. Inside function: hello Outside function: <empty>
D. Runtime error: variable s not found

Solution

  1. Step 1: Analyze ownership transfer in function call

    The function take_ownership takes ownership of s, so s is moved into the function.
  2. Step 2: Check usage of s after function call

    After the call, s is no longer valid in main, so using it causes a compile error.
  3. Final Answer:

    Inside function: hello Compile error: use of moved value 's' -> Option A
  4. Quick Check:

    Ownership moved, use after move = compile error [OK]
Hint: Using moved variable after function call causes compile error [OK]
Common Mistakes:
  • Assuming variable is copied automatically
  • Expecting output after ownership moved
  • Ignoring Rust's ownership rules
4. Identify the error in this Rust code and how to fix it:
fn calculate_length(s: String) -> usize {
    s.len()
}

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(s1);
    println!("The length of '{}' is {}.", s1, len);
}
medium
A. Error: s1 is moved into calculate_length; fix by passing &s1 instead.
B. Error: calculate_length returns wrong type; fix by returning &usize.
C. Error: println! macro syntax incorrect; fix by removing quotes.
D. No error; code runs and prints length correctly.

Solution

  1. Step 1: Identify ownership issue in function call

    calculate_length takes ownership of s1, so s1 is moved and invalid after call.
  2. Step 2: Fix by borrowing s1 instead of moving

    Change function parameter to &String and pass &s1 to avoid moving ownership.
  3. Final Answer:

    Error: s1 is moved into calculate_length; fix by passing &s1 instead. -> Option A
  4. Quick Check:

    Pass reference to avoid moving ownership [OK]
Hint: Pass references to keep ownership when calling functions [OK]
Common Mistakes:
  • Trying to return reference to local variable
  • Ignoring ownership move on function parameters
  • Misunderstanding borrowing syntax
5. You want to write a function that takes ownership of a vector, doubles each element, and returns ownership back. Which function signature and body correctly implement this in Rust?
hard
A. fn double_vec(v: &Vec<i32>) -> Vec<i32> { v.iter().map(|x| x * 2).collect() }
B. fn double_vec(v: Vec<i32>) -> Vec<i32> { v.iter().map(|x| x * 2).collect() }
C. fn double_vec(v: Vec<i32>) { for x in &v { println!("{}", x * 2); } }
D. fn double_vec(v: &mut Vec<i32>) { for x in v { *x *= 2; } }

Solution

  1. Step 1: Understand ownership and return requirements

    The function must take ownership of the vector and return ownership back after doubling elements.
  2. Step 2: Analyze each option for ownership and functionality

    fn double_vec(v: Vec<i32>) -> Vec<i32> { v.iter().map(|x| x * 2).collect() } takes ownership (Vec<i32>), creates a new doubled vector, and returns it, satisfying requirements.
  3. Final Answer:

    fn double_vec(v: Vec<i32>) -> Vec<i32> { v.iter().map(|x| x * 2).collect() } -> Option B
  4. Quick Check:

    Take ownership, return new doubled vector [OK]
Hint: Take Vec ownership and return new Vec after processing [OK]
Common Mistakes:
  • Borrowing vector but not returning ownership
  • Not returning anything from function
  • Modifying borrowed vector without ownership
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard