Skip to chapter content
navan✳THE BUILD LABRUST / GUIDE
0/26 read
CHAPTER 05 / 21 · DATA AND MODELS

Borrowing and slices.

Understand shared reads, exclusive writes, and views into existing data.

BY NAVAN SAMILONG READRUST 2024THEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

A reference is temporary access to a value owned elsewhere. An immutable reference &T permits reading while leaving ownership with the original binding. A mutable reference &mut T permits mutation, but Rust requires it to be exclusive for the relevant period. This rule prevents a reader from observing a value while another path changes it in an uncontrolled way.

The lifetime of a borrow is the region where that reference may still be used. Modern borrow checking follows actual uses, not just the nearest closing brace, so a shared borrow can finish before a later mutable borrow begins. The compiler does not merely dislike mutation; it requires an unambiguous moment when mutation is allowed. The signature of a function reveals this: &T says read, &mut T says edit, and T says own.

02 / THE RULES

What Rust is checking.

A slice is a borrowed view of a contiguous sequence. &str views UTF-8 text; &[T] views elements. The slice carries a pointer and a length, so it can describe a portion without allocating a new collection. It cannot outlive the owner of those elements. If a string or vector changed in a way that invalidated its storage while a slice was active, the slice would become unsafe; Rust's borrowing rules stop that combination.

When explaining an example, draw a timeline: owner created, reference formed, last use of reference, owner dropped. Then mark whether each reference is shared or exclusive. This timeline is more useful than thinking of references as raw addresses. It shows why two reads can coexist, why a writer needs a clear turn, and why returning a reference to a local temporary is invalid.

03 / CODE, EXPLAINED

See the rule in context.

Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.

EXAMPLE 01

Shared references & borrowing

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.

borrowing.rs
fn characters(text: &str) -> usize {
    text.chars().count()
}
fn main() {
    let name = String::from("Navan");
    let size = characters(&name);
    println!("{name}: {size} characters");
}
OUTPUT
Navan: 5 characters
  1. &name borrows instead of moving the String.
  2. The String reference can coerce to &str.
  3. The caller still owns name after the function returns.

The boundary: String::len counts UTF-8 bytes, while chars().count counts Unicode scalar values; neither automatically counts user-visible graphemes.

EXAMPLE 02

Mutable references

A mutable reference &mut T grants exclusive access for the duration of that active borrow. You cannot simultaneously use a conflicting shared or mutable reference. The rule is about aliasing plus mutation, not about banning all mutation. Once a borrow’s last use has passed, the owner can be accessed again. Keep mutable borrows short and near the operation they support. If you need disjoint parts of a collection, use APIs such as split_at_mut that express the non-overlap to the compiler.

mutable-borrows.rs
fn append_ready(text: &mut String) {
    text.push_str(" ready");
}
fn main() {
    let mut task = String::from("server");
    append_ready(&mut task);
    let values = [1, 2, 3, 4].map(|n| n * 2);
    let (left, right) = values.split_at(2);
    println!("{task}");
    println!("{} {}", left[0], right[0]);
}
OUTPUT
server ready
2 6
  1. The owner is declared mut because it will be changed.
  2. The function receives a temporary exclusive borrow.
  3. The later print runs after the mutation borrow has ended.

The boundary: Do not keep a reference alive across an operation that may invalidate it, such as Vec::push reallocating the buffer.

EXAMPLE 03

Slices & string boundaries

A slice &[T] describes a contiguous range using a pointer and a length. It borrows the elements rather than copying them. A string slice &str additionally guarantees valid UTF-8. String range indexes refer to bytes and must fall on UTF-8 character boundaries. get on a string range returns None for invalid bounds or a split inside a code point, while direct indexing by such a range panics. Work with chars for scalar iteration and a Unicode-aware crate when your product needs grapheme segmentation.

slices.rs
fn main() {
    let values = [10, 20, 30, 40];
    let middle = &values[1..3];
    let text = "café";
    println!("{middle:?}");
    println!("prefix={:?}, broken={:?}", text.get(..3), text.get(..4));
}
OUTPUT
[20, 30]
prefix=Some("caf"), broken=None
  1. The array slice covers indexes 1 and 2.
  2. The accented é occupies two UTF-8 bytes.
  3. The ..4 boundary splits that character, so get returns None.

The boundary: A slice cannot outlive its underlying collection. Return an owned value if the source must be dropped.

04 / THE CONNECTION

Keep this model.

Borrowing separates access from ownership. Shared reads and exclusive writes are enforced for the time references are live.

Finished reading?
Built with curiosity. By Navan Sami. ↗Rust · The rules behind the code.