What Is Borrowing in Rust? Immutable References Explained

Borrowing in Rust allows read-only access to data via immutable references without transferring ownership.

Borrowing in Rust is the mechanism that allows you to use a value without taking ownership of it, and an immutable reference (&T) lets you read that data without changing it. You create an immutable reference by prefixing a variable with &, which grants read-only access while the original owner retains control.

fn main() {
    let s1 = String::from("hello");
    let s2 = &s1; // Borrow s1 immutably
    println!("{s1}, {s2}");
}

You can have multiple immutable references to the same data at the same time, but you cannot modify the data through any of them.