typestar

Collecting into anything in Rust

collect builds whatever type you ask for — map, string, or Result.

use std::collections::HashMap;

fn main() {
    let pairs = [("python", 6), ("rust", 11)];
    let tours: HashMap<&str, i32> = pairs.into_iter().collect();
    println!("{}", tours["rust"]);

    let letters: String = ["ru", "st"].into_iter().collect();
    println!("{letters}");

    let good: Result<Vec<i32>, _> =
        ["1", "2", "3"].iter().map(|s| s.parse::<i32>()).collect();
    let bad: Result<Vec<i32>, _> =
        ["1", "no"].iter().map(|s| s.parse::<i32>()).collect();
    println!("{:?} {}", good, bad.is_err());
}

How it works

  1. The target type drives which collection is built.
  2. Collecting into Result stops at the first error.
  3. An iterator of pairs collects straight into a HashMap.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
483
Tokens
214
Three-star pace
100 tpm

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

Type this snippet

Step 2 of 3 in Terminal operations, step 10 of 14 in Iterators & closures.

← Previous Next →