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
parseneeds a target type, given by annotation or turbofish.unwrap_orsupplies a default for the error case.filter_mapkeeps only the values that parsed.
Keywords and builtins used here
Vecf64fni32letmain
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.
Step 2 of 3 in Text, step 28 of 39 in Language basics.