All lessons

Lesson 6 of 11

Borrowing

Read through a shared reference and update through a mutable reference.

main.rs

fn main() {    let mut name = String::from("Ferris");    let reader = &name;    println!("{reader}");    let editor = &mut name;    editor.push('!');    println!("{name}");}

Program state

References
None
Step 1 of 7

The program is ready to create an owned String.

What’s happening

The & operator creates a shared reference, which lets you read a value while the original binding keeps ownership. Several shared references can overlap.

A mutable reference created with &mut gives exclusive access while it is active. Rust tracks where references are used, so a borrow can end after its last use, before the closing brace.

See an example the compiler rejects
fn main() {    let mut name = String::from("Ferris");    let reader = &name;    let editor = &mut name;    editor.push('!');    println!("{reader}");}

The final println! still needs reader, so its shared borrow is active when editor tries to borrow name mutably. Those borrows cannot overlap.

Read more in The Rust Book