typestar

Ownership across functions in Rust

A function can take ownership, borrow, or hand ownership back.

fn consume(text: String) -> usize {
    text.len()
}

fn inspect(text: &String) -> usize {
    text.len()
}

fn hand_back(mut text: String) -> String {
    text.push_str("!");
    text
}

fn main() {
    let greeting = String::from("welcome");
    println!("{}", inspect(&greeting));
    let greeting = hand_back(greeting);
    println!("{}", consume(greeting));
}

How it works

  1. Taking String consumes the caller's value.
  2. Taking &String borrows and leaves it usable.
  3. Returning the value passes ownership back out.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
332
Tokens
106
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 71 seconds.

Type this snippet

Step 3 of 3 in Move & clone, step 3 of 15 in Ownership & borrowing.

← Previous Next →