Ownership rules in Rust - Time & Space Complexity
Ownership rules in Rust control how data is accessed and managed in memory.
We want to understand how these rules affect the speed of running Rust programs.
Analyze the time complexity of the following Rust code snippet.
fn calculate_length(s: String) -> (String, usize) {
let length = s.len();
(s, length)
}
fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("Length: {}", len);
}
This code moves ownership of a string to a function, calculates its length, and returns both.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
len()on the string to get its length. - How many times: Once per function call, no loops or recursion here.
Rust's String::len() retrieves a stored length value in constant time (O(1)). Ownership moves are also O(1) as they involve pointer adjustments without copying data.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | O(1) |
| 100 | O(1) |
| 1000 | O(1) |
Pattern observation: The work remains constant regardless of the string length.
Time Complexity: O(1)
This means the time to get the string length remains constant, independent of the string size.
[X] Wrong: "Ownership transfers make the program slower because data is copied every time."
[OK] Correct: Ownership moves just transfer control without copying data, so they don't add extra time.
Understanding ownership helps you write safe and efficient Rust code, a skill that shows you know how to manage resources well.
"What if the function borrowed the string instead of taking ownership? How would the time complexity change?"
Practice
Solution
Step 1: Understand ownership move
When ownership moves, the original variable loses its right to access the data.Step 2: Effect on original variable
The original variable becomes invalid and cannot be used to prevent double free errors.Final Answer:
The original variable becomes invalid and cannot be used. -> Option AQuick Check:
Ownership move invalidates old owner = A [OK]
- Thinking ownership move copies data
- Assuming both variables remain valid
- Confusing move with borrowing
Solution
Step 1: Identify borrowing syntax
Immutable borrowing uses the & symbol before the variable.Step 2: Match correct syntax
let x = &value; correctly borrows value immutably.Final Answer:
let x = &value; -> Option DQuick Check:
Immutable borrow uses & = B [OK]
- Using * for borrowing instead of dereferencing
- Missing & symbol for borrowing
- Confusing mutable and immutable borrow syntax
let s1 = String::from("hello");
let s2 = s1;
println!("{}", s1);Solution
Step 1: Analyze ownership move
Assigning s1 to s2 moves ownership, invalidating s1.Step 2: Using invalidated variable
Printing s1 after move causes a compile-time error because s1 is no longer valid.Final Answer:
Compilation error -> Option CQuick Check:
Using moved variable causes compile error = A [OK]
- Expecting s1 to print after move
- Confusing move with copy
- Thinking runtime error occurs instead
let s = String::from("hello");
let r1 = &s;
let r2 = &mut s;
println!("{} and {}", r1, r2);Solution
Step 1: Check borrowing rules
Rust forbids mutable borrow if immutable borrow exists simultaneously.Step 2: Identify conflict
r1 is an immutable borrow; r2 tries mutable borrow causing error.Final Answer:
Cannot borrow s as mutable because it is already borrowed as immutable. -> Option BQuick Check:
Mutable borrow conflicts with existing immutable borrow = D [OK]
- Ignoring borrow rules and expecting code to run
- Thinking multiple mutable borrows allowed
- Misunderstanding println! macro usage
fn take_ownership(s: String) {
println!("{}", s);
}
fn main() {
let s = String::from("hello");
take_ownership(s);
println!("{}", s);
}
What is the correct way to fix the error without cloning the string?Solution
Step 1: Understand ownership transfer
Passing s to take_ownership moves ownership, invalidating s in main.Step 2: Use borrowing to avoid move
Changing parameter to &String borrows s, so ownership stays with main.Step 3: Adjust function call
Call take_ownership(&s) to pass reference matching new parameter.Final Answer:
Change the function parameter to borrow the string: fn take_ownership(s: &String) -> Option AQuick Check:
Borrow parameter to keep ownership in caller = C [OK]
- Trying to use s after move without borrowing
- Removing code instead of fixing ownership
- Confusing mutability with ownership
Ready to prove it?
Pass the test and this pattern moves unknown
