On-Ramp to Rust

borrowing and references

If passing a value to a function moves it and makes the original unusable, programming would be painful — every function that wanted to look at your String would swallow it. The everyday fix is borrowing: instead of handing over ownership, you let a function look at your value through a reference, and when it is done, you still own the value. It is exactly like lending a friend a book to read versus giving it away — they get to use it, then it comes back to you, and you remain the owner who is responsible for it.

A reference is Rust's word for a controlled pointer: it is an address that lets code read (and sometimes write) a value it does not own. You create one with the & operator — &x produces a reference to x — and a function that takes &String receives a borrow rather than ownership, so calling it does not move your value. There are two flavours. A shared reference, written &T, lets the borrower read the value but not change it; you can hand out many shared references at once because read-only sharing is harmless. A mutable reference, written &mut T, lets the borrower change the value, and Rust permits only one of those at a time. The reference itself is checked: it must always point at a valid, still-living value, which is what makes a Rust reference safer than a raw C pointer that can dangle.

Why this matters: borrowing is what makes ownership livable. Without it, every read of a value would consume it; with it, you keep ownership and lend out temporary, compiler-checked access. This is the same distinction a careful C programmer draws between a pointer that takes ownership (the receiver must free it) and a pointer that merely borrows (the receiver must not free it) — except Rust writes the difference into the types (&T versus T) and the compiler enforces it. The single most important rule that comes with borrowing — many shared borrows or one mutable borrow, never both — is important enough to get its own entry next.

fn len(s: &String) -> usize { // borrows, does not take ownership s.len() } let name = String::from("ada"); let n = len(&name); // lend a reference println!("{name} has {n} chars"); // name is STILL usable here

Pass &name to lend the value; the caller keeps ownership and can use name afterwards.

A reference is not the value and does not own it — it is borrowed access that must outlive nothing it points to. Borrowing never frees the value; only the owner does, when its scope ends.

Also called
reference&T&mut T借用參考引用