Borrowing in Rust
References let you use a value without owning it.
fn total(items: &[i32]) -> i32 {
items.iter().sum()
}
fn push_one(items: &mut Vec<i32>) {
items.push(1);
}
fn main() {
let mut nums = vec![10, 20, 30];
let sum = total(&nums);
push_one(&mut nums);
println!("{sum} {}", nums.len());
}
How it works
&[i32]borrows immutably to read.&mut Vecborrows mutably to modify.- The owner keeps the value after the borrow ends.
Keywords and builtins used here
Vecfni32letmainmutpush_onetotal
The run, in numbers
- Lines
- 14
- Characters to type
- 234
- Tokens
- 92
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 58 seconds.
Step 1 of 3 in Borrowing, step 4 of 15 in Ownership & borrowing.