What is borrowing in Rust

Borrowing in Rust lets you access data via references without taking ownership, enforcing strict rules to prevent data races and ensure memory safety.

Borrowing in Rust is the mechanism that allows you to use a value without taking ownership of it, preventing data duplication and ensuring memory safety. You create an immutable reference with & to read data or a mutable reference with &mut to change it, but you can only have one mutable reference or any number of immutable references at a time.

fn main() {
    let mut s = String::from("hello");
    let r1 = &s; // Immutable borrow
    let r2 = &s; // Another immutable borrow
    println!("{} and {}", r1, r2);
    // r1 and r2 are no longer used here
    let r3 = &mut s; // Mutable borrow
    r3.push_str(", world");
    println!("s: {}", s);
}