Borrowing and slices.
Understand shared reads, exclusive writes, and views into existing data.
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.
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.
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.
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.
fn characters(text: &str) -> usize {
text.chars().count()
}
fn main() {
let name = String::from("Navan");
let size = characters(&name);
println!("{name}: {size} characters");
}Navan: 5 characters
- &name borrows instead of moving the String.
- The String reference can coerce to &str.
- 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.
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.
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]);
}server ready 2 6
- The owner is declared mut because it will be changed.
- The function receives a temporary exclusive borrow.
- 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.
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.
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));
}[20, 30]
prefix=Some("caf"), broken=None- The array slice covers indexes 1 and 2.
- The accented é occupies two UTF-8 bytes.
- 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.
Keep this model.
Borrowing separates access from ownership. Shared reads and exclusive writes are enforced for the time references are live.