Vectors, arrays and hash maps

Vec, slices, HashMap with the entry API, sorting, and iterator chains with filter, map and collect.

Runs in Zerethon IDE · Rust 1.87 Official Rust documentation ↗
main.rs
use std::collections::HashMap;

fn main() {
    let mut scores = vec![70, 95, 82];
    scores.push(60);
    let mut sorted = scores.clone();
    sorted.sort();
    println!("{:?} {} {} {}", sorted, scores[0], scores[scores.len() - 1], scores.len());
    println!("{:?} {}", &sorted[1..3], scores.contains(&95));

    let mut ages: HashMap<&str, i32> = HashMap::new();
    ages.insert("ada", 36);
    ages.insert("alan", 41);
    *ages.entry("grace").or_insert(0) += 85;
    println!("{:?} {}", ages.get("linus"), ages.contains_key("alan"));
    let mut names: Vec<_> = ages.keys().collect();
    names.sort();
    for name in names {
        println!("{name} {}", ages[name]);
    }

    let squares: Vec<i32> = (0..5).filter(|n| n % 2 == 0).map(|n| n * n).collect();
    println!("{:?}", squares);

    let mut people = vec![("bob", 25), ("amy", 31)];
    people.sort_by(|a, b| b.1.cmp(&a.1));
    println!("{:?}", people);
}

Output

[60, 70, 82, 95] 70 60 4
[70, 82] true
None true
ada 36
alan 41
grace 85
[0, 4, 16]
[("amy", 31), ("bob", 25)]
  • vec![...] creates a Vec; it must be mut to push or sort.
  • v[i] stops the program when i is out of range; v.get(i) returns an Option instead.
  • HashMap iteration order is random. Collect and sort the keys when the order matters, or use BTreeMap, which keeps keys sorted.
  • Iterator methods are lazy: nothing happens until collect(), sum(), a for loop or similar consumes them.