Rust:Rust References and Borrowing (& and &mut)
Rust•Borrowing

Rust References and Borrowing (& and &mut)

Borrowing allows referencing data without taking ownership. The borrow checker prevents data races at compile time.

Syntax

fn calculate_len(s: &String) -> usize {} fn append_data(s: &mut String) {}

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
&TImmutable ReferenceZero-cost read-only borrow.
&mut TMutable ReferenceExclusive mutable borrow.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

// Borrowing immutably
fn calculate_length(s: &String) -> usize {
    s.len()
}

// Borrowing mutably
fn append_status(s: &mut String) {
    s.push_str(" [VERIFIED]");
}

fn main() {
    let mut message = String::from("Payload 101");

    // Multiple immutable borrows are allowed
    let len1 = calculate_length(&message);
    let len2 = calculate_length(&message);
    println!("Calculated lengths: {} and {}", len1, len2);

    // One exclusive mutable borrow
    append_status(&mut message);
    println!("Updated message: {}", message);
}
Expected Output:
Calculated lengths: 11 and 11
Updated message: Payload 101 [VERIFIED]

How It Works: Step-by-Step

  • Lines 2-4: calculate_length borrows s immutably without taking ownership.
  • Lines 7-9: append_status borrows s mutably with &mut String.
  • Line 20: Original message remains valid and modified in place.

Key Concepts

  • Borrowing rule 1: You can have any number of immutable references (&T).
  • Borrowing rule 2: You can have only ONE mutable reference (&mut T) at a time.
  • References must always be valid (no dangling pointers).

Common Mistake: Having both an immutable reference and a mutable reference in the same scope

Rust forbids reading while another reference is mutating (prevents data races).

❌ Incorrect
let mut s = String::from("a"); let r1 = &s; let r2 = &mut s; println!("{}", r1); // Compile Error!
✅ Correct
let mut s = String::from("a"); let r1 = &s; println!("{}", r1); let r2 = &mut s; // Non-overlapping

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler