Rust Systems & Tokio (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
What is Borrowing and what are the Borrow Checker Rules?
junior LevelCode ExamplerustBasic
In Simple Words:
Instead of transferring ownership, a function or variable can borrow a reference using &:
- Rule 1: You may have any number of immutable references (
&T) to a resource at a given time. - Rule 2: OR you may have exactly one mutable reference (
&mut T) at a given time. - Rule 3: References must always be valid (the data cannot be dropped while a reference exists).
- Eliminates Data Races at compile time!
rust
let mut data = vec![1, 2, 3];
let r1 = &data; // Immutable borrow
let r2 = &data; // OK: Multiple readers
// let r3 = &mut data; // COMPILE ERROR: Cannot borrow as mutable while immutable borrows exist!