Rust provides a borrowing system to access data without transferring ownership.
Rust provides a borrowing system to access data without transferring ownership.
The &
symbol signifies a borrow.
let s = String::from("hello");
let borrowed_s = &s;
Borrowing comes in two flavors: immutable and mutable.
An immutable borrow lets you read data, but not change it.
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
A mutable reference lets you alter data.
Only one mutable reference is allowed within a scope.
This ensures no data races.
let mut s = String::from("hello");
let r1 = &mut s;
// let r2 = &mut s; // Error: data race potential!
Multiple immutable borrows can coexist, but not alongside a mutable borrow.
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
// let r3 = &mut s; // This would be an error!
Dangling is when a reference reference's data gets freed while the reference still exists.
Rust ensures references never "dangle".
let r;
{
let s = String::from("hello");
r = &s;
} // `s` drops here, making `r` a dangling reference.
Slices let you reference collection parts, not the entire collection.
This way, you can work with collection segments without owning the whole thing.
This allows for flexible and safe data access.
let str = String::from("Hello, World!");
let hello_slice = &str[0..5]; // hello_slice = "Hello"
let world_slice = &str[7..12]; // world_slice = "World"
Rust promotes safe data handling through its borrowing mechanism, allowing data access without complete ownership transfer:
Immutable references: Read data without altering. Multiple immutable references can coexist unless there's a mutable reference.
Mutable references: Modify data. Only one is allowed per scope.
Dangling references: Rust ensures all references point to valid data.
Slices: Let you reference collections in parts
The power of Rust's ownership and borrowing rules lies in ensuring memory safety and data integrity without the need for a garbage collector. Please check out the Rust Book.