Move Ownership Through Function Returns
Returned values move out of the function into the caller, shown by the compile-time dead bindings and by borrowing the result afterwards.
Code
fn build_label(id: u32) -> String {
// String 在这里构造,返回时 move 出函数作用域
format!("item-{id}")
}
fn take_and_report(label: String) -> usize {
// label 按值接管,调用方此后不能再用原绑定
let len = label.len();
println!("received {label}");
len
}
fn main() {
let label = build_label(7);
println!("owner says: {label}");
// move 进函数:label 从这里失效,再读会编译报错
let len = take_and_report(label);
println!("reported length: {len}");
// println!("{label}"); // E0382:值已被 move
// 返回值归调用方所有:可以继续借出去
let shout = format!("{}!!", build_label(9).to_uppercase());
println!("{shout}");
}How it works
The snippet is organized around the functions build_label, take_and_report and main.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
Signature: fn build_label(id: u32) -> String
The run prints received, owner says:, reported length: — each prefix names the step that produced it.
Start the program and main runs build_label and take_and_report one after another.
Key statements
fn take_and_report(label: String) -> usize {
// label 按值接管,调用方此后不能再用原绑定
let len = label.len();
println!("received {label}");
len
}
fn build_label(id: u32) -> String {
// String 在这里构造,返回时 move 出函数作用域
format!("item-{id}")
}
Interactive Tools for This Topic
FAQ
- What does Move Ownership Through Function Returns print when run?
- Invoke the file as-is — the `received`, `owner says:`, `reported length:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.