ownership

Rust Return an owned value

A function can transfer ownership to its caller by returning an owned value. The value is not destroyed just because the local name in the function disappears. Expected output (not executed): Box 4 Why: The returned String becomes owned by parcel. Common mistake: Trying to return a reference to the local String instead of the owned value.

Formal Syntax & Structure

rust syntaxrust
fn make() -> String { ... }

Working Example

Example Snippetrust
fn make_label() -> String {    let label = String::from("Box 4");    label}fn main() {    let parcel = make_label();    println!("{parcel}");}
Rust Reference