typestar

Parsing text in Rust

Turning strings into numbers, and deciding what a failure means.

fn main() {
    let count: i32 = "42".parse().unwrap();
    let ratio = "3.5".parse::<f64>().unwrap_or(0.0);
    println!("{count} {ratio}");

    let raw = "10,x,30,4";
    let nums: Vec<i32> = raw
        .split(',')
        .filter_map(|part| part.parse().ok())
        .collect();
    println!("{:?} sum {}", nums, nums.iter().sum::<i32>());
}

How it works

  1. parse needs a target type, given by annotation or turbofish.
  2. unwrap_or supplies a default for the error case.
  3. filter_map keeps only the values that parsed.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
299
Tokens
117
Three-star pace
90 tpm

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

Type this snippet

Step 2 of 3 in Text, step 28 of 39 in Language basics.

← Previous Next →