Sub topic 5
Parsing Input into Numbers and Other Types
This chapter assumes you can already read a line into a String with read_line, handle its io::Result, and trim the trailing newline. It also assumes you know match, Result, and the difference between String and &str. Here you turn the text into typed values and handle the ways that conversion fails.
Input is always text
Everything read from standard input is bytes interpreted as text. If a user types 42, your program receives the characters 4 and 2, not the integer 42. Converting text to a value is called parsing, and Rust does it with str::parse.
use std::io;
fn main() {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
let age: u32 = match input.trim().parse() {
Ok(n) => n,
Err(e) => {
println!("Not a valid number: {e}");
return;
}
};
println!("Next year you will be {}.", age + 1);
}The signature of parse is:
pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>Three facts follow from it:
parseis a method onstr. AStringworks because it dereferences to&str.- The result type
Fis any type that implements theFromStrtrait. The standard library implements it for integers, floats,bool,char, andString. - The error type belongs to
F. Parsing au32fails with aParseIntError, and parsing anf64fails with aParseFloatError.
Telling Rust which type you want
parse cannot guess the target type. You supply it in one of two ways.
fn main() {
let a: i32 = "10".parse().unwrap(); // annotation on the binding
let b = "2.5".parse::<f64>().unwrap(); // turbofish on the call
println!("{}", a as f64 * b);
}The ::<f64> form is called the turbofish. Use it when there is no binding to annotate, for example in the middle of an expression. If you give neither, the compiler reports type annotations needed. The type can also be inferred from later use, such as passing the result to a function that takes u8.
The pipeline
Reading and parsing form a short pipeline. The line you read still carries its newline, so trimming comes first.
What parsing accepts and rejects
Parsing is strict. Most surprises come from input that looks fine to a human but is not exactly what FromStr expects. This program shows how u8 handles several inputs:
fn main() {
let samples = ["42", " 42", "42\n", "", "-5", "+7", "300", "4_2"];
for s in samples {
match s.parse::<u8>() {
Ok(n) => println!("{s:?} -> Ok({n})"),
Err(e) => println!("{s:?} -> Err({e})"),
}
}
}It prints:
"42" -> Ok(42)
" 42" -> Err(invalid digit found in string)
"42\n" -> Err(invalid digit found in string)
"" -> Err(cannot parse integer from empty string)
"-5" -> Err(invalid digit found in string)
"+7" -> Ok(7)
"300" -> Err(number too large to fit in target type)
"4_2" -> Err(invalid digit found in string)The rules for integers are:
- Surrounding whitespace is an error, including the newline left by
read_line. This is why you calltrimfirst. - An empty string is its own error.
- A leading
+is allowed. A leading-is allowed only for signed types. Foru8,-5is an invalid digit. - A value outside the type's range is an overflow error, not a wrapped value.
- Underscores, thousands separators, and prefixes such as
0xare rejected. Usei32::from_str_radix(text, 16)for other bases.
Floats follow similar rules but accept more forms:
fn main() {
for s in ["3.14", "1e3", ".5", "nan", "inf", "1,5", ""] {
match s.parse::<f64>() {
Ok(n) => println!("{s:?} -> Ok({n:?})"),
Err(e) => println!("{s:?} -> Err({e})"),
}
}
}"3.14" -> Ok(3.14)
"1e3" -> Ok(1000.0)
".5" -> Ok(0.5)
"nan" -> Ok(NaN)
"inf" -> Err(invalid float literal)Wait: that last line is wrong. inf is accepted, so the real output continues like this:
"inf" -> Ok(inf)
"1,5" -> Err(invalid float literal)
"" -> Err(cannot parse float from empty string)The other built-in types are stricter:
| Target type | Error type | Accepts |
|---|---|---|
| `i32`, `u64`, and other integers | `ParseIntError` | Optional sign and decimal digits only |
| `f32`, `f64` | `ParseFloatError` | Decimals, exponents, `nan`, `inf` |
| `bool` | `ParseBoolError` | Exactly `true` or `false`, lowercase |
| `char` | `ParseCharError` | Exactly one character |
| `String` | `Infallible` | Any text, so it can never fail |
For example, "True".parse::<bool>() is an error. If you want yes/no or y/n, write a match on the lowercased text instead of calling parse.
Responding to the kind of failure
ParseIntError hides its details, but kind() returns an IntErrorKind that lets you give a specific message:
use std::num::IntErrorKind;
fn describe(text: &str) -> String {
match text.trim().parse::<i8>() {
Ok(n) => format!("ok: {n}"),
Err(e) => match e.kind() {
IntErrorKind::Empty => "nothing entered".to_string(),
IntErrorKind::InvalidDigit => "not a whole number".to_string(),
IntErrorKind::PosOverflow => "too big (max 127)".to_string(),
IntErrorKind::NegOverflow => "too small (min -128)".to_string(),
_ => "unusable number".to_string(),
},
}
}
fn main() {
for s in ["12", "", "abc", "200", "-200"] {
println!("{s:?}: {}", describe(s));
}
}IntErrorKind is marked #[non_exhaustive], so the compiler requires the _ arm. Future Rust versions may add variants without breaking your code.
Parsing several values from one line
A line often holds several values, such as 3 4 5. Splitting on whitespace and parsing each token gives an iterator of Results. Collecting that iterator into a Result<Vec<_>, _> gives one overall result. It stops at the first error and returns it.
use std::str::FromStr;
fn parse_all<T: FromStr>(line: &str) -> Result<Vec<T>, T::Err> {
line.split_whitespace().map(str::parse::<T>).collect()
}
fn main() {
println!("{:?}", parse_all::<i32>("3 4 5"));
println!("{:?}", parse_all::<i32>("3 x 5"));
println!("{:?}", parse_all::<f64>("1.5 2.5"));
}This prints Ok([3, 4, 5]), then Err(ParseIntError { kind: InvalidDigit }), then Ok([1.5, 2.5]). The bound T: FromStr lets one function handle every parseable type, and T::Err carries whichever error that type produces. A later chapter covers split_whitespace in more detail.
Parsing your own types
Because parse works for any FromStr type, you can add the same behavior to your own types. This Point reads text like 3,4:
use std::io;
use std::str::FromStr;
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl FromStr for Point {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (xs, ys) = s.split_once(',').ok_or("expected x,y")?;
let x = xs.trim().parse::<i32>().map_err(|e| format!("bad x: {e}"))?;
let y = ys.trim().parse::<i32>().map_err(|e| format!("bad y: {e}"))?;
Ok(Point { x, y })
}
}
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
match input.trim().parse::<Point>() {
Ok(p) => println!("Got {p:?}"),
Err(msg) => println!("Invalid point: {msg}"),
}
Ok(())
}Typing 3, 4 prints Got Point { x: 3, y: 4 }. Typing 3;4 prints Invalid point: expected x,y. The ? operator inside from_str converts the &str error into a String through the From trait. Keeping the parsing logic in from_str separates it from the reading logic, so you can test it with plain string literals.
Common mistakes
- Forgetting
trim."42\n".parse::<u32>()fails with an invalid digit error, and the message does not mention the newline. If every valid input fails, suspect this first. - Using
unwraporexpecton user input. These panic on the first typo. They are fine in quick experiments, but real programs should match on theResult. - Using
?in amainthat returnsio::Result<()>. AParseIntErrordoes not convert into anio::Error, so the code does not compile. Handle the error withmatch, or change the return type toResult<(), Box<dyn Error>>. A later chapter covers that return type. - Picking too small a type. Parsing into
u8rejects300, and parsing intou32rejects-1. Choose a type that fits the values users may reasonably enter. - Trusting parsed floats. A successful parse of
nanorinfis still a validf64.
Exercise
Why does "42\n".parse::<u32>() return an error, and what is the smallest change that makes it work?
Show answer
parse requires the whole string to be a number, and the newline is not a digit, so it fails with an invalid digit error. Call trim first: "42\n".trim().parse::<u32>() returns Ok(42).
Exercise
Write a function parse_percent(text: &str) -> Result<u8, String> that trims the text, parses it as a u8, and returns an error message if the result is above 100. A failed parse should also return a String error.
Show answer
fn parsepercent(text: &str) -> Result<u8, String> { let n = text.trim().parse::<u8>().maperr(|e| format!("not a number: {e}"))?; if n > 100 { Err(format!("{n} is above 100")) } else { Ok(n) } }
Exercise
A user types -3 into a program that parses with parse::<u32>(). Which IntErrorKind do you get, and why is it not NegOverflow?
Show answer
You get InvalidDigit. For unsigned types, a leading minus sign is not accepted as part of the number, so the - is treated as an invalid character. NegOverflow is reported only for signed types when a negative number is below the type's minimum, such as -200 for i8.