Rust FAQ: Top Questions
4. What is borrowing in Rust?
Borrowing allows functions to access variables without taking ownership. This is done through references. Borrowing can be immutable or mutable.
- Immutable Borrow: Allows multiple readers.
- Mutable Borrow: Allows one writer.
fn main() {
let mut message = String::from("Hello");
change(&mut message);
println!("{}", message);
}
fn change(text: &mut String) {
text.push_str(", world!");
}
Explanation: Rust enforces borrowing rules to avoid data races and dangling references. You can't have mutable and immutable borrows active at the same time.
