Ownership and Functions
How ownership transfers when passing values to functions.
Ownership and Functions
How ownership transfers when passing values to functions.
Difficulty
Beginner
Code
fn take_ownership(s: String) {
println!("took ownership of: {}", s);
}
fn give_back(s: String) -> String {
println!("giving back: {}", s);
s
}
fn main() {
let s = String::from("hello");
take_ownership(s);
// s is no longer valid here
let s2 = String::from("world");
let s3 = give_back(s2);
println!("got back: {}", s3);
}Explanation
Passing values to functions moves ownership. Functions can return ownership.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the ownership category to build a complete understanding of this topic.