Return ownership in Rust by placing the variable name as the final expression in the function body without a semicolon to move the value to the caller.
Return ownership by listing the variable name as the final expression in the function body without a semicolon. This moves the value out of the function scope to the caller.
fn gives_ownership() -> String {
let some_string = String::from("yours");
some_string
}
fn takes_and_gives_back(a_string: String) -> String {
a_string
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len();
(s, length)
}
Returning ownership means handing over the responsibility for a piece of data to the code that called your function. Think of it like passing a physical object to someone; once you hand it over, you no longer have it, and they become responsible for it. This prevents two parts of your program from trying to use or delete the same data at the same time.