RUST / CHAPTER 03
Borrowing and slices
IntermediateUse references to inspect or mutate data without taking ownership.
By the end of this chapter
- Distinguish shared and mutable references
- Use slices for borrowed sequences
- Recognize conflicting live borrows
The idea
Enter with ownership transfers understood. A shared reference borrows a value for reading without becoming its owner. A mutable reference permits mutation, but overlapping uses must obey Rust’s aliasing rules: either shared access or exclusive mutable access to the same place. The compiler checks the lifetimes during which references are actually used, so the end of a borrow need not be the closing brace.
Slices describe a borrowed contiguous portion of a sequence. An &[i32] parameter accepts arrays and vectors through borrowing without requiring a particular owning collection. An &str similarly borrows UTF-8 text. Indexing a Rust string by an integer is unavailable because a byte offset is not necessarily a character boundary. Match the interface to the information the helper needs.
fn total(values:&[i32])->i32 { values.iter().sum() }
fn main(){
let mut values=vec![2,4,6];
values[1]+=1;
println!("{}",total(&values[1..]));
}11
The slice borrows the last two elements, now five and six. The helper reads them without consuming the vector.
Try it yourself
Write a function accepting &mut [i32] that replaces every negative value with zero.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING