Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. Borrowing / References (&)

Borrowing / References (&)

Borrowing is a mechanism for passing a reference to a value without transferring ownership. You can hold multiple immutable references (&T) at the same time, but only one mutable reference (&mut T) at a time.

Syntax

// Immutable reference (read-only)
let r = &variable;
fn function_name(arg: &Type) { ... }

// Mutable reference (read and write)
let r = &mut variable;
fn function_name(arg: &mut Type) { ... }

Borrowing Rules

RuleDescription
Multiple immutable references allowedYou can create any number of &T references at the same time.
Only one mutable reference at a timeOnly one &mut T can exist at a time (prevents data races).
Immutable and mutable cannot coexistYou cannot hold both &T and &mut T at the same time.
No dangling referencesA reference cannot outlive the value it refers to (verified by the compiler).

Sample Code

fn print_length(s: &String) {
    println!("Length: {}", s.len()); // Borrows ownership just to read the value.
}

fn append_world(s: &mut String) {
    s.push_str(", world"); // Can modify the value through a mutable reference.
}

fn main() {
    let s = String::from("hello");

    // Multiple immutable references can be created at the same time.
    let r1 = &s;
    let r2 = &s;
    println!("{} and {}", r1, r2);

    print_length(&s); // Ownership is not transferred.
    println!("{}", s); // s is still usable.

    // Mutable reference
    let mut s2 = String::from("hello");
    append_world(&mut s2);
    println!("{}", s2); // Prints "hello, world".

    // Only one mutable reference at a time.
    let r3 = &mut s2;
    // let r4 = &mut s2; // Error: cannot have two mutable references at the same time.
    println!("{}", r3);
}

Overview

The borrow checker validates the validity of references at compile time. This allows issues such as null references and dangling pointers to be detected before the program runs.

Using a mutable reference and an immutable reference in the same scope at the same time causes a compile error. However, starting with Rust Edition 2018, "Non-Lexical Lifetimes (NLL)" applies, allowing a new reference to be created after the last use of an existing reference.

For details on reference lifetimes, see Lifetimes ('a).

If you find any errors or copyright issues, please .