Borrowing
Borrowing is access to a value without a transfer of ownership. The expression &x creates a reference to x: a function or another variable can now read the value, while x stays the owner and is still the one that will free the memory. This removes the awkwardness from the Ownership topic: to look at a String, you no longer have to move it into a function and hand it back.
References come in two kinds. A shared reference &T allows only reading, and there can be any number of them. A mutable reference &mut T allows changing the value, but while it is alive nobody else touches the value — not even its owner. This "many readers or one writer" rule is checked by the borrow checker, a part of the compiler, and thanks to it safe Rust has no data races and no iterator invalidation. The second rule is that a reference always points to a live value, so a dangling reference does not compile. A borrow lasts not until the end of the block but until the reference's last use. Slices &[T] and &str are references too: they borrow not the whole value but a contiguous part of an array, a vector or a string. This topic walks borrowing layer by layer — from a plain reference to string slices.
Topic map
- References —
&xborrows a value without a transfer of ownership;*dereferences; methods andprintln!dereference on their own; a reference is never null. - Mutable References —
&mut xallows changing the value through the reference; the variable must be declared withmut, otherwise E0596; writing through*r = …;let mut r = &xandlet r = &mut xare different things. - Borrowing Rules — many
&Tor one&mut T; errors E0499 and E0502; why the rule rules out data races and iterator invalidation; a borrow ends at its last use; reborrowing. - Dangling References — a reference cannot outlive its value; errors E0597, E0106 and E0515; instead of a reference to a local variable, a function returns the value itself.
- Slices —
&[T]is an address and a length; rangesa..b,..b,a..and..; going past the end is a panic; the mutable slice&mut [T]; a&[T]parameter accepts both an array and a vector. - String Slices —
&strlooks at UTF-8 bytes; a string literal has the type&'static str; slice bounds are byte indices, and a bound in the middle of a character panics; a&Stringturns into a&stron its own, so the parameter is written as&str.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Taking &mut s of a variable declared without mut | error[E0596]: cannot borrow `s` as mutable, as it is not declared as mutable |
Holding &v[0], or looping with for x in &v, and calling v.push(…) | error[E0502]: push may move the elements into a new buffer, and the reference would point into freed memory |
Taking two &mut to one value and using both | error[E0499]: cannot borrow `s` as mutable more than once at a time |
Returning a reference to a String created inside the function | error[E0106] or error[E0515]: the string is freed on return; return the String itself |
Slicing a string in the middle of a character: &"привет"[0..1] | The panic end byte index 1 is not a char boundary at runtime: the letter "п" takes two bytes |
Declaring a &String or &Vec<T> parameter | The function will not accept a literal, an array or part of a collection; &str and &[T] are idiomatic |
Why it matters in interviews
Borrowing, together with ownership, is the central topic of a junior Rust interview: without it you cannot explain a single borrow checker error. What gets checked is not the syntax of & and &mut but an understanding of which bugs the "many readers or one writer" rule rules out, and why the compiler rejects code that in C++ would build and crash later.
What interviewers usually check:
- The borrowing rules: many
&Tor one&mut T— and why a&mutmust be the only one. - Why
v.push(…)does not compile while a reference to a vector element is alive or afor x in &vloop is running. - What non-lexical lifetimes changed: a borrow ends at the reference's last use, not at the end of the block.
- What a dangling reference is, and why you cannot return a
&strto aStringcreated inside the function. - What a slice is, and why
&s[0..2]is a range of bytes rather than characters. - Why a parameter is written as
&stror&[T]rather than&Stringor&Vec<T>.