typestar

Ownership and move in Rust

Every value has one owner; passing it moves it.

fn takes_ownership(s: String) -> usize {
    s.len()
}

fn main() {
    let text = String::from("hello");
    let n = takes_ownership(text);
    // `text` has moved into the function; only `n` remains

    let a = String::from("keep");
    let b = a.clone();
    println!("{n} {a} {b}");
}

How it works

  1. Passing a String moves it into the function.
  2. After a move the original binding is unusable.
  3. clone makes an independent copy to keep both.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
261
Tokens
71
Three-star pace
90 tpm

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

Type this snippet

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

Next →