Borrowing lets you use data without taking full ownership. This helps avoid mistakes and keeps your program safe and fast.
Why borrowing is required in Rust
Introduction
Syntax
Rust
&variable or &mut variable
&variable means borrowing data to read only (immutable borrow).
&mut variable means borrowing data to change it (mutable borrow).
Examples
x to read its value without taking ownership.Rust
let x = 5; let y = &x; // borrow x immutably println!("{}", y);
x to change its value safely.Rust
let mut x = 5; let y = &mut x; // borrow x mutably *y += 1; println!("{}", x);
Sample Program
This program shows borrowing to read and change a string without moving ownership.
Rust
fn main() {
let mut name = String::from("Alice");
greet(&name); // borrow name to read
change_name(&mut name); // borrow name to change
greet(&name);
}
fn greet(name: &String) {
println!("Hello, {}!", name);
}
fn change_name(name: &mut String) {
name.push_str(" Smith");
}Important Notes
Borrowing helps Rust catch bugs at compile time before running the program.
You cannot have mutable and immutable borrows of the same data at the same time.
Borrowing avoids copying data, which makes programs faster and use less memory.
Summary
Borrowing lets you use data safely without taking ownership.
Use & for reading and &mut for changing data.
Borrowing helps prevent bugs and improves performance.
Practice
1. Why does Rust require borrowing when accessing data instead of always transferring ownership?
easy
Solution
Step 1: Understand ownership and borrowing
Ownership means one variable controls the data. Borrowing lets others use data without owning it.Step 2: Why borrowing is useful
Borrowing allows multiple parts of code to read data safely without making copies or moving ownership.Final Answer:
To allow multiple parts of code to read data without copying it -> Option AQuick Check:
Borrowing = safe shared access [OK]
Hint: Borrowing means sharing data without moving ownership [OK]
Common Mistakes:
- Thinking borrowing slows down code
- Believing borrowing prevents all data changes
- Confusing borrowing with copying data
2. Which of the following is the correct syntax to borrow a variable immutably in Rust?
easy
Solution
Step 1: Identify borrowing syntax
In Rust, borrowing immutably uses the ampersand before the variable:&value.Step 2: Match correct syntax
The correct way to bind a reference islet x = &value;. Other options are invalid or mean something else.Final Answer:
let x = &value; -> Option BQuick Check:
Immutable borrow = &value [OK]
Hint: Use & before variable to borrow immutably [OK]
Common Mistakes:
- Using let x = ref value; invalid syntax
- Confusing &x with &value
- Using mutable borrow (&mut) for immutable access
3. What will be the output of this Rust code?
fn main() {
let s = String::from("hello");
let r1 = &s;
let r2 = &s;
println!("{} and {}", r1, r2);
}medium
Solution
Step 1: Analyze borrowing in code
Two immutable referencesr1andr2borrowssimultaneously, which is allowed.Step 2: Check output of println!
Both references print the string "hello", so output is "hello and hello".Final Answer:
hello and hello -> Option AQuick Check:
Multiple immutable borrows print values [OK]
Hint: Multiple immutable borrows allowed, prints values [OK]
Common Mistakes:
- Thinking multiple immutable borrows cause errors
- Confusing mutable and immutable borrow rules
- Expecting runtime errors for borrowing
4. Identify the error in this Rust code and why borrowing is required:
fn main() {
let mut s = String::from("hello");
let r1 = &s;
let r2 = &mut s;
println!("{} and {}", r1, r2);
}medium
Solution
Step 1: Check borrowing rules
Rust forbids mutable borrow while immutable borrow exists to prevent data races.Step 2: Identify error cause
Here,r1immutably borrowss, thenr2tries mutable borrow, causing compile error.Final Answer:
Cannot borrow `s` as mutable because it is already borrowed as immutable -> Option CQuick Check:
Mutable borrow blocked by existing immutable borrow [OK]
Hint: Mutable borrow blocked if immutable borrow exists [OK]
Common Mistakes:
- Thinking mutable borrow is allowed with immutable borrow
- Ignoring borrow checker errors
- Assuming println! causes error
5. You want to write a function that changes a string passed to it without taking ownership. Which borrowing type should you use and why?
hard
Solution
Step 1: Understand function parameter needs
To modify data inside a function without taking ownership, you must borrow it mutably.Step 2: Choose correct borrow type
Mutable borrow&mutallows changing the original data safely without moving ownership.Final Answer:
Mutable borrow (&mut) because it allows modifying the string without ownership -> Option DQuick Check:
Modify data = use &mut borrow [OK]
Hint: Use &mut to change data without ownership transfer [OK]
Common Mistakes:
- Using immutable borrow when modification is needed
- Transferring ownership unnecessarily
- Copying data instead of borrowing
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
