Small Programs · 11 min · free with an account

First References

Lesson preview · about 30%

A shared reference lets a function read a value while the caller keeps ownership.

Core idea

&T borrows T for read-only use without transferring ownership.

Start with the idea

The & symbol creates a borrow. A shared reference such as &str permits reading but not mutation, and it does not own the value it points to. Passing a reference avoids a move, so the original binding remains usable after the call. Later ownership lessons add the precise aliasing rules and mutable references.

In the example, name owns a String. Passing &name to length creates a shared borrow, and the parameter text: &str lets the function read the bytes through that borrow. length returns a usize, not the text itself. After the call ends, main still owns name and can print it. No second owned String had to be made for this read-only question.

A reference is valid only while the value it refers to is available. Rust checks that relationship so code cannot keep a pointer into a value that has already gone away. Shared references permit reading; mutation through a shared reference is not allowed.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Basics