Skip to main content
Be Bitwise
RustBorrowing & Lifetimes

References & Borrowing

Borrowing lets you use a value without owning it. It's Rust's answer to a question every C programmer asks five minutes in: how do I let a function read my data without surrendering it?

Shared References

A reference is created with &:

rust
fn calculate_length(s: &String) -> usize {
s.len()
}
let s = String::from("hello");
let len = calculate_length(&s); // borrow s
println!("{} has length {}", s, len); // s is still valid

&s makes a reference that borrows s. The function reads the data; ownership stays where it was.

The Borrowing Rules

  1. As many shared references (&T) as you like, simultaneously.
  2. Exactly one mutable reference (&mut T) at any moment.
  3. Shared and mutable references can't coexist for the same value.
rust
let s = String::from("hello");
let r1 = &s;
let r2 = &s; // OK: multiple shared references
println!("{} {}", r1, r2);
// let r3 = &mut s; // ERROR: cannot borrow as mutable while shared refs exist
Key Concept

The rules eliminate data races at compile time. A race needs simultaneous reads and writes against the same memory; Rust's "many readers OR one writer, never both" makes that combination unrepresentable in safe code.

Returning References

rust
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &byte) in bytes.iter().enumerate() {
if byte == b' ' {
return &s[..i];
}
}
&s[..]
}
let sentence = String::from("hello world");
let word = first_word(&sentence);
println!("First word: {}", word);

The function borrows a string slice and hands back a sub-slice into the same buffer. The compiler tracks that the returned reference can't outlive the input — the lifetime is tied implicitly.

Dereferencing

In most contexts the compiler dereferences for you:

rust
let x = 5;
let r = &x;
println!("{}", r); // auto-deref: prints 5
assert_eq!(*r, 5); // explicit deref with *

Method calls on references get the same treatment:

rust
let s = String::from("hello");
let r = &s;
println!("{}", r.len()); // auto-deref: calls s.len()

Which is why explicit * operators are rare in Rust source. The compiler quietly handles the indirection for you.

Now test yourself on the rules. Lines A, B and C are commented out: decide which would compile, then uncomment them one at a time and compare the errors with your guesses.

Try itUncomment A, B or C, run, then put the comment back before trying the next.
Rust (1.40.0)
Show the answer

None of them compile. A takes &mut s while r1 and r2 are still used on the next line (E0502). B takes a second &mut s while m1 is about to be used (E0499). C reads s after it moved into consume (E0382).