C.W.K.
Stream
Lesson 01 of 05 · published

References — Borrowing Without Owning

~11 min · borrowing, references, immutable

Level 0Rust Curious
0 XP0/80 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete

The ownership track ended on a frustration: to let a function read your data, you had to give it away and get it back. References fix that. A reference lets you use a value without owning it — borrow it, look, and let it go automatically.

The & operator

&s creates a reference to s without taking ownership. Pass &s to a function and the function borrows the value: it can read it, but ownership stays with the caller. When the reference goes out of scope, nothing is dropped — you only borrowed it.

Borrowing in function signatures

A parameter of type &String (or better, &str) says 'I want to read this, not own it.' The caller keeps the value after the call returns. This is the default you'll reach for constantly: take a reference unless you genuinely need ownership.

Borrow by default; take ownership only when you must. Most functions only need to read or temporarily use data. A reference says exactly that, and it leaves the caller's value intact — no moves, no returning-just-to-give-it-back.

References are not the dangerous kind of pointer

A Rust reference is guaranteed to point at valid data for as long as it exists — the compiler proves it. There's no null reference, no dangling reference, no 'is this still alive?' A reference is a promise the borrow checker enforces, not a raw address you have to babysit.

Code

Borrow to read, keep ownership·rust
fn length(s: &String) -> usize {
    s.len() // read through the reference
} // s goes out of scope, but it's only a reference — nothing dropped

fn main() {
    let name = String::from("Ferris");
    let len = length(&name);   // lend a reference
    // name is STILL valid here — we only borrowed it
    println!("{name} is {len} chars");
}

External links

Exercise

Rewrite the awkward loudest function from the Ownership track to take &[String] (a borrowed slice) instead of Vec<String>, so it no longer needs to return the vec. Confirm the caller can still use its vector after the call.
Hint
When the function only reads the data, borrow it with &. The caller keeps ownership, so there's nothing to return — the move-and-give-back dance disappears.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Ttoriwarm

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.