typestar

Working a Vec in Rust

The Vec methods that do real work: filtering in place, sorting by key, windows.

fn main() {
    let mut words = vec!["pear", "fig", "apple", "kiwi", "plum"];

    words.retain(|w| w.len() > 3);
    words.sort_by_key(|w| w.len());
    println!("{:?}", words);

    let nums = [1, 3, 6, 10, 15];
    for pair in nums.windows(2) {
        print!("{} ", pair[1] - pair[0]);
    }
    println!();

    for chunk in nums.chunks(2) {
        print!("{:?}", chunk);
    }
    println!();
}

How it works

  1. retain keeps the elements whose test passes.
  2. sort_by_key sorts by a derived value.
  3. windows and chunks view a slice in overlapping or fixed groups.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
341
Tokens
143
Three-star pace
90 tpm

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

Type this snippet

Step 2 of 8 in Collections, step 31 of 39 in Language basics.

← Previous Next →