Click a card to flip it · 8 terms
Borrowing lets you use a value without taking ownership. This deck covers shared and mutable references, the rules enforced by the borrow checker, and how Rust prevents dangling references.
A read-only reference, use a value without taking ownership
When a function only needs to read a value
let s = String::from("hi");let r = &s; // borrow, s still valid
A read-write reference, use and change a value
When a function needs to modify a value
let mut s = String::from("hi");let r = &mut s;
Rust's built-in system that enforces borrowing rules at compile time
When you try to have two mutable references to the same value
let r1 = &s; // ok// let r2 = &mut s; // error
Follow a reference to get the actual value it points to
*count += 1;, required when you want to modify the value behind a &mut reference
*count += 1;
&mut
let mut x = 5;let r = &mut x; *r += 1;
The block a variable lives in, between { and }
{
}
Determines when a value is dropped
{ let x = 5; }// x is dropped, determines its lifetime
How long a reference stays valid, compiler tracks this automatically
Rust tracks this automatically; you rarely write lifetimes yourself
let s = String::from("hi");let r = &s; // r lives as long as s
One mutable reference OR many immutable ones; all references must be valid
When you accidentally mix mutable and immutable references to the same value
let r1 = &s; let r2 = &s; // ok// &mut s here → error
A reference pointing to data that's already been freed
When a function tries to return a reference to a local variable
fn dangle() -> &String {let s = String::from("x"); &s }