typestar

Vectors in Rust

The growable Vec and its everyday methods.

fn main() {
    let mut nums = vec![3, 1, 4, 1, 5];
    nums.push(9);
    nums.sort();
    nums.dedup();

    let first = nums.first().copied().unwrap_or(0);
    let total: i32 = nums.iter().sum();
    let slice = &nums[1..3];
    println!("{first} {total} {}", slice.len());
}

How it works

  1. vec! builds one; push appends.
  2. sort and dedup reorder and compact in place.
  3. iter().sum() and slicing read across it.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
245
Tokens
99
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 66 seconds.

Type this snippet

Step 1 of 8 in Collections, step 30 of 39 in Language basics.

← Previous Next →