← Back to Rust Course | Chapter 6: Borrowing & References | Lesson 1 of 6

References Basics

A reference lets you look at someone else's value and use it, without actually owning it yourself.

Creating a Reference

Prefixing a variable with & creates a reference to its value instead of moving or copying it. The function receiving the reference can read the data without owning it.

Example: Creating a Reference

markup
fn print_value(v: &i32) {
    println!("Value is {}", v);
}

fn main() {
    let number = 42;
    print_value(&number);
    println!("Still usable: {}", number);
}

References to Strings

References are especially useful for larger data like String, letting a function read the content without taking ownership away from the caller.

Example: References to Strings

markup
fn print_length(s: &String) {
    println!("Length: {}", s.len());
}

fn main() {
    let name = String::from("Ferris");
    print_length(&name);
    println!("name is still valid: {}", name);
}

References Are Immutable by Default

A plain reference &value only allows reading, not writing, the data it points to. This matches the default immutability of let bindings.

Example: References Are Immutable by Default

markup
fn main() {
    let data = vec![1, 2, 3];
    let reference = &data;
    println!("Through reference: {:?}", reference);
}

The Original Owner Remains Valid

Because borrowing with & does not transfer ownership, the original variable remains fully usable both during and after the borrow, unlike a move.

Example: The Original Owner Remains Valid

markup
fn describe(s: &String) {
    println!("Describing: {}", s);
}

fn main() {
    let word = String::from("borrow");
    describe(&word);
    describe(&word);
    println!("word used three times total: {}", word);
}
Common Mistakes
  1. Forgetting the & when calling a function that expects a reference, causing a type mismatch error.
  2. Assuming a reference is a copy of the data -- it is only a pointer to the original value, not a new value.
  3. Trying to modify data through an immutable reference, which the compiler rejects.
Chapter Summary
  • A reference, written &value, lets you access a value without taking ownership of it.
  • References are immutable by default, just like let bindings.
  • Referencing a value instead of passing it by value is called borrowing.
  • The referenced value's owner is unaffected and can still be used after the borrow ends.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.