Borrowing and References
Use values without taking ownership.
Learning objectives
- Create immutable references
- Create mutable references safely
- Understand borrowing rules
Borrowing
Borrowing allows a function or variable to use a value without taking ownership of it. This is done with references.
Immutable References
An immutable reference lets you read a value but not change it.
Mutable References
A mutable reference lets you change a value. Rust restricts mutable borrowing to prevent data races and conflicting changes.
Example code
fn print_length(text: &String) {
println!("Length: {}", text.len());
}
fn add_word(text: &mut String) {
text.push_str(" programming");
}
fn main() {
let mut language = String::from("Rust");
print_length(&language);
add_word(&mut language);
println!("{}", language);
}
Practice task: Write a function that borrows a String and prints it in uppercase without taking ownership.