Sub topic 2
Passing and Borrowing Ownership in Rust
Assume basic Rust syntax, String, Vec, functions, and the difference between stack and heap data. This chapter focuses on how functions transfer or temporarily use ownership.
Passing and Returning Ownership
A function parameter can take ownership. When you pass a String by value, the value moves into the function. The caller cannot use it afterward unless the function returns it.
fn add_exclamation(mut text: String) -> String {
text.push('!');
text
}
fn main() {
let message = String::from("hello");
let message = add_exclamation(message);
println!("{message}");
}The function owns text, changes it, and returns ownership. The caller binds the returned value again.
Borrowing with Shared References
A shared reference, written &T, lends access without transferring ownership. The function can read the value but cannot change it.
fn length(text: &str) -> usize {
text.len()
}
fn main() {
let message = String::from("hello");
println!("{} bytes", length(&message));
println!("{message}");
}The &message expression creates a shared borrow. message remains owned by main.
Borrowing with Mutable References
A mutable reference, written &mut T, permits changes without transferring ownership. The owner must be declared mut.
fn add_suffix(text: &mut String) {
text.push_str(", Rust");
}
fn main() {
let mut message = String::from("hello");
add_suffix(&mut message);
println!("{message}");
}Borrowing Rules and the Borrow Checker
Rust checks these rules at compile time:
- Any number of shared references may exist.
- Only one mutable reference may exist at a time.
- Shared and mutable references cannot overlap.
- A reference must not outlive the value it refers to.
Slices as Borrowed Views
A slice is a reference to part of a collection. A string slice, &str, can view some or all of a String.
fn first_word(text: &str) -> &str {
text.split_whitespace().next().unwrap_or("")
}
fn main() {
let text = String::from("ownership matters");
let word = first_word(&text);
println!("{word}");
}The returned slice borrows from text, so it cannot remain valid after text is dropped.
Exercise
Why does fn length(text: String) prevent the caller from using its original String, while fn length(text: &str) does not?
Show answer
Passing String moves ownership into the function. Passing &str creates a temporary shared borrow, so the caller retains ownership.