Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ OWNERSHIP WITHOUT THE PANIC
BUILD NOTE 11 / 53

Read without taking over.

Let functions inspect values while the caller keeps ownership.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

A shared reference &T borrows a value without transferring ownership. Several shared references can coexist because safe Rust prevents conflicting ordinary mutation during those active borrows. A reference must not outlive its referent. Rust often ends a borrow after its last use, rather than waiting for the closing brace; this is why a later mutation can be allowed once earlier reads are finished. Prefer parameters such as &str or &[T] when a function only needs a view rather than ownership of a particular container.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/borrowing/src/main.rs
fn characters(text: &str) -> usize {
    text.chars().count()
}
fn main() {
    let name = String::from("Navan");
    let size = characters(&name);
    println!("{name}: {size} characters");
}
↳ EXPECTED OUTPUT
Navan: 5 characters
  1. 1

    &name borrows instead of moving the String.

  2. 2

    The String reference can coerce to &str.

  3. 3

    The caller still owns name after the function returns.

From the extracted rust-workbench folder
cargo run -p lesson_borrowing

03 Mind the boundary

04 Your next build

A SMALL MISSION

Write a function accepting &[i32] and return the sum without consuming the collection.

Reveal one possible solution +
solutions/borrowing/src/main.rs
fn sum(values: &[i32]) -> i32 {
    values.iter().sum()
}
fn main() {
    let values = vec![2, 4, 6];
    assert_eq!(sum(&values), 12);
    assert_eq!(values.len(), 3);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Does passing &String transfer ownership of the String?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.