Sub topic 5
Parsing input into numbers and other types
This chapter assumes you can already call read_line into a String, handle its io::Result with expect or ?, and trim the trailing newline. Here you turn that text into typed values.
Text is not a number
Everything from standard input arrives as text. The input 42 is the two characters 4 and 2, not an integer. The str::parse method converts text into another type. It returns a Result, because the conversion can fail.
Choosing the target type
parse is generic over its return type, so the compiler must know which type you want. You can say so in two ways.
- Turbofish:
input.trim().parse::<u32>() - Type annotation on the binding:
let age: u32 = ...
Here is a complete program that uses the turbofish and handles both outcomes.
use std::io;
fn main() {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
match input.trim().parse::<u32>() {
Ok(age) => println!("Next year you will be {}.", age + 1),
Err(e) => println!("Not a valid number: {e}"),
}
}Without the type, the compiler reports type annotations needed. That error means parse has no way to infer what you want.
How parse works
parse works for any type that implements the FromStr trait. The standard library implements it for all integer and float types, bool, char, and String. The error type depends on the target: ParseIntError, ParseFloatError, ParseBoolError, and so on. The following program prints the result for each case.
fn main() {
println!("{:?}", "3.14".parse::<f64>());
println!("{:?}", "true".parse::<bool>());
println!("{:?}", "x".parse::<char>());
println!("{:?}", "300".parse::<u8>());
}This prints:
Ok(3.14)
Ok(true)
Ok('x')
Err(ParseIntError { kind: PosOverflow })You can implement FromStr for your own types. Then "..." .parse::<MyType>() works the same way.
What fails and why
Parsing is strict. The whole string must be a valid value, with nothing extra.
| Text | Target | Result |
|---|---|---|
| `42` | `u32` | `Ok(42)` |
| `+5` | `i32` | `Ok(5)` |
| `-5` | `u32` | Error: invalid digit |
| `3.5` | `i32` | Error: invalid digit |
| `3.5` | `f64` | `Ok(3.5)` |
| empty string | `i32` | Error: cannot parse integer from empty string |
| `300` | `u8` | Error: number too large to fit in target type |
| `7` with a leading space | `i32` | Error: invalid digit |
The last row is the most common mistake in beginner programs. read_line keeps the newline, so "42\n".parse::<i32>() fails. Call trim() first.
Passing the error up
Inside a function that returns Result, the ? operator can propagate the parse error. That works only if the function's error type can hold it. io::Error and ParseIntError are different types, so a plain io::Result return type will not compile with ? on a parse. The simplest fix is to handle the parse error locally with match. A later chapter on Box<dyn Error> shows how to return both kinds of error.
use std::io;
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let n: i64 = match input.trim().parse() {
Ok(n) => n,
Err(e) => {
eprintln!("bad number {:?}: {e}", input.trim());
return Ok(());
}
};
println!("double is {}", n * 2);
Ok(())
}Here ? handles the I/O error and match handles the parse error. Printing the offending text with {:?} shows hidden characters such as stray spaces.
Common errors
- Forgetting
trim(), so a valid number fails because of the newline. - Picking an unsigned type such as
u32and then entering a negative number. - Picking a type that is too small, which overflows with
PosOverfloworNegOverflow. - Parsing a decimal like
2.5as an integer type. - Omitting the type, which gives
type annotations needed.
Exercise
What does " 12 ".parse::<i32>() return, and how do you make it succeed?
Show answer
It returns an Err (invalid digit), because parse rejects surrounding whitespace. Call trim() first: " 12 ".trim().parse::<i32>() returns Ok(12).
Exercise
Write the type annotation form of parsing a trimmed String named s into an f64 named price.
Show answer
let price: f64 = s.trim().parse().expect("not a number"); In a real program, prefer match over expect so bad input does not panic.