Transfer ownership through functions
Quick answer
Passing a non-Copy value to a function by value transfers ownership to the parameter. Returning that value (or another owned value) transfers ownership back to the caller.
Inputs and outputs as ownership boundaries
A parameter of type String owns its input, unlike a parameter of reference type introduced in the next chapter. If the function finishes without returning or moving the String elsewhere, it is normally dropped. A Copy argument is copied rather than invalidated. Choose an owning parameter when the operation really needs ownership.
fn consume(message: String) { println!("received: {message}"); }fn main() { let note = String::from("hello"); consume(note);}Expected stdout (not executed):
received: helloThe function owns note's previous value. The caller cannot use note after this call.
fn decorate(mut text: String) -> String { text.push('!'); text}fn main() { let original = String::from("ready"); let updated = decorate(original); println!("{updated}");}Expected stdout (not executed):
ready!The function appends one character and returns the owned String.
Common mistake
A function call does not automatically return ownership of its arguments. The signature must return the value if the caller needs it.
Try it yourself
Write a function that takes a String, appends a question mark and returns it.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Transfer ownership through functions — practice quiz
Choose one answer per question, then review the explanation.
A function takes a String and returns that same String. Who owns the returned value?
An i32 is passed by value to a function. Can the caller still use its binding?
When should an API take an owned String instead of simply reading it?