typestar

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

  1. &[i32] borrows immutably to read.
  2. &mut Vec borrows mutably to modify.
  3. The owner keeps the value after the borrow ends.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Borrowing, step 4 of 15 in Ownership & borrowing.

← Previous Next →