All lessons

Lesson 5 of 11

Ownership

Follow a String as ownership moves from one binding to another.

main.rs

fn main() {    let first = String::from("Ferris");    let second = first;    println!("{second}");}

Program state

Text buffer
Unallocated
Step 1 of 5

The program has yet to allocate a String.

What’s happening

A String owns a buffer where it stores its text. Assigning first to second moves ownership of that String. Rust prevents you from using first after the move.

When second goes out of scope, Rust drops the String and releases its buffer. Some types such as i32 implement Copy, so assigning them leaves both bindings usable.

See an example the compiler rejects
fn main() {    let first = String::from("Ferris");    let second = first;    println!("{first} and {second}");}

The compiler reports a use after move. Printing first tries to borrow a String whose ownership already moved to second.

Read more in The Rust Book