Ad space (banner)
Lesson 10 / 20

Borrowing (references, &)

This lesson covers borrowing, which lets you use a value without moving ownership.

Writing &value creates a reference to it. A reference lets you pass a value to a function without moving ownership, so the original variable stays usable.

The sample code passes a reference to a string into fn calculate_length(s: &String) -> usize and confirms that the caller can still use s afterwards.

A common early stumble is knowing when to pass the value itself (which moves it) and when to pass a reference (which only borrows). "If you only need to read the value, use a reference" is a good rule of thumb.

In professional work, borrowing is used constantly to hand large pieces of data to a function without copying them.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Rust directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)