Understanding Ownership: Who Owns the Data?
Level: intro (score: 1)
One of the biggest differences between Rust and Python is ownership. Unlike Python, Rust does not have a garbage collector—instead, it enforces strict ownership rules at compile time to manage memory safely. Each value has a single owner at any given time. Once ownership is transferred, the previous owner cannot use the value anymore—this prevents memory issues like dangling pointers.
Why This Matters
In Python, you can pass a string around freely without worrying about ownership:
def greet(name):
return f"Welcome, {name}!"
username = "Alice"
message = greet(username)
print(username) # Still accessible
However, in Rust, ownership means the original variable is moved when passed into a function, and trying to use it afterward results in a compile-time error.
Task
Implement the function: transfer_ownership(name: String) -> String
- The function should take ownership of a
String
parameter and return a newly constructed string that includes it. - The original variable should no longer be usable after passing it into the function.
Hints
- Use
format!
to construct the return value. - Try running (compiling) a version where you use the original variable after calling the function—Rust will guide you on what went wrong!
let username = String::from("Alice");
let message = transfer_ownership(username);
// Uncommenting the next line will cause a compile-time error!
// println!("{}", username); // value borrowed after move
Mastering ownership is the key to writing safe and efficient Rust code.
No garbage collector needed—just smart rules that ensure memory safety at compile time. 💡
Happy coding! 🚀