Sub topic 11
Parsing strings into other types
This chapter assumes you know basic Rust syntax, ownership and borrowing, and how Option and Result work. It also assumes you have seen split_once and trim from the previous chapter on searching and splitting. Here you will turn text into numbers, booleans, and your own types, and handle the errors that come with it.
Why parsing returns a Result
Text from files, command-line arguments, and network input arrives as a &str or String. To use it as a number, you must check that it has the right shape. Any string can fail that check, so Rust does not cast text to numbers. It gives you a method that returns a Result.
The standard tool is str::parse:
fn main() {
let n: Result<i32, _> = "42".parse::<i32>();
let bad = "forty-two".parse::<i32>();
println!("{:?}", n);
println!("{:?}", bad);
}The first line prints Ok(42). The second prints Err(ParseIntError { kind: InvalidDigit }).
How parse works: FromStr
parse is a generic method. Its signature is roughly fn parse<F: FromStr>(&self) -> Result<F, F::Err>. The target type F must implement the FromStr trait, which has one method, from_str. Each type that implements it also picks its own error type, F::Err.
Rust must know F at compile time. You can supply it in three ways:
fn double(x: u64) -> u64 {
x * 2
}
fn main() {
// 1. Turbofish on parse
let a = "10".parse::<u64>();
// 2. Type annotation on the binding
let b: Result<u64, _> = "20".parse();
// 3. Inference from later use
let c = "30".parse().map(double);
println!("{:?} {:?} {:?}", a, b, c);
}Without one of these, the compiler reports "type annotations needed". You can also call the trait directly with u64::from_str("10"), but that needs use std::str::FromStr;.
What the built-in types accept
Each standard type has its own rules, and some surprise people.
| Target type | Accepts | Rejects |
|---|---|---|
| Signed integers (`i32`) | Optional `+` or `-`, then digits | Spaces, `_`, `0x` prefixes, empty string |
| Unsigned integers (`u8`) | Optional `+`, then digits | `-1` (even `-0`), spaces, empty string |
| Floats (`f64`) | `3.14`, `.5`, `1.`, `1e3`, `inf`, `NaN` | Spaces, `1,5`, empty string |
| `bool` | Exactly `true` or `false` | `True`, `1`, `yes` |
| `char` | A string of exactly one `char` | Empty or longer strings |
| `String` | Anything (never fails) | Nothing |
Two rules matter most. First, parsing does not trim whitespace. " 42".parse::<i32>() fails. Second, u8 also checks the range, so "300" fails because it overflows.
Reading integer errors
ParseIntError has a kind() method that returns an IntErrorKind. This lets you give precise feedback or recover from specific cases.
use std::num::IntErrorKind;
fn main() {
for text in ["42", " 42", "+7", "-1", "", "300", "12abc"] {
match text.parse::<u8>() {
Ok(n) => println!("{text:?} -> {n}"),
Err(e) => match e.kind() {
IntErrorKind::Empty => println!("{text:?}: empty"),
IntErrorKind::InvalidDigit => println!("{text:?}: bad digit"),
IntErrorKind::PosOverflow => println!("{text:?}: too big for u8"),
_ => println!("{text:?}: other error"),
},
}
}
}The output is:
"42" -> 42
" 42": bad digit
"+7" -> 7
"-1": bad digit
"": empty
"300": too big for u8
"12abc": bad digitIntErrorKind is marked #[non_exhaustive], so the match needs a catch-all arm. The kinds are Empty, InvalidDigit, PosOverflow, NegOverflow, and Zero. Zero applies only to the NonZero types.
For another base, use from_str_radix:
fn main() {
println!("{:?}", i64::from_str_radix("ff", 16));
println!("{:?}", u8::from_str_radix("1010", 2));
println!("{:?}", i32::from_str_radix("0xff", 16).is_err());
}This prints Ok(255), Ok(10), and true. The function does not accept the 0x prefix, so you must strip it yourself, for example with strip_prefix("0x").
Float and other errors
Floats use ParseFloatError, booleans use ParseBoolError, and char uses ParseCharError. These are opaque. You can print them, but you cannot inspect a kind. Parsing succeeds for "inf" and "NaN", so check is_finite() if you must reject them.
fn main() {
for text in ["3.14", "1e3", ".5", "inf", "1,5", ""] {
match text.parse::<f64>() {
Ok(x) => println!("{text:?} -> {x} finite={}", x.is_finite()),
Err(e) => println!("{text:?} -> error: {e}"),
}
}
}Parsing floats is locale-independent. The decimal separator is always ., so "1,5" fails. If you need locale-aware numbers, handle that before calling parse.
Propagating errors with ?
Every parse error type implements std::error::Error. This means Box<dyn Error> can hold any of them, and ? converts them automatically:
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let width: u32 = "80".parse()?;
let ratio: f64 = "0.5".parse()?;
let verbose: bool = "true".parse()?;
println!("{width} {ratio} {verbose}");
let height: u32 = "tall".parse()?;
println!("unreachable: {height}");
Ok(())
}The last ? returns early and the program exits with an error message that includes invalid digit found in string. In library code, prefer a specific error type over Box<dyn Error>. The next section shows one.
Implementing FromStr for your own type
Implementing FromStr makes "...".parse::<MyType>() work. Combine split_once with parse and give the type a real error enum:
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32,
}
#[derive(Debug, PartialEq)]
enum ParsePointError {
MissingComma,
BadNumber(ParseIntError),
}
impl From<ParseIntError> for ParsePointError {
fn from(e: ParseIntError) -> Self {
ParsePointError::BadNumber(e)
}
}
impl FromStr for Point {
type Err = ParsePointError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (x, y) = s.split_once(',').ok_or(ParsePointError::MissingComma)?;
Ok(Point {
x: x.trim().parse()?,
y: y.trim().parse()?,
})
}
}
fn main() {
println!("{:?}", "3, 4".parse::<Point>());
println!("{:?}", "3;4".parse::<Point>());
println!("{:?}", "3,x".parse::<Point>());
}The output is:
Ok(Point { x: 3, y: 4 })
Err(MissingComma)
Err(BadNumber(ParseIntError { kind: InvalidDigit }))The From impl lets ? convert a ParseIntError into ParsePointError. The type of each parse() call is inferred from the struct field. Take &str, not String, in from_str, so the parser never forces an allocation.
Parsing many values
To parse a list, map each piece and collect into Result<Vec<_>, _>. Collecting stops at the first error:
use std::num::ParseIntError;
fn parse_all(input: &str) -> Result<Vec<i32>, ParseIntError> {
input.split(',').map(|p| p.trim().parse::<i32>()).collect()
}
fn main() {
println!("{:?}", parse_all("1, 2, 3"));
println!("{:?}", parse_all("1, two, 3"));
// Skip bad items instead of failing
let lenient: Vec<i32> = "1, two, 3"
.split(',')
.filter_map(|p| p.trim().parse().ok())
.collect();
println!("{:?}", lenient);
}The first call returns Ok([1, 2, 3]), the second returns the InvalidDigit error, and the lenient version gives [1, 3]. Choose strict collection when bad data means the whole input is wrong. Choose filter_map only when you are sure silently dropping items is acceptable, because it hides data problems.
Going the other way
Converting values to text uses Display. Any type that implements Display gets to_string() for free, and format! works too:
fn main() {
let n = 255;
let s = n.to_string();
let hex = format!("{n:x}");
println!("{s} {hex} {}", s.parse::<i32>().unwrap() == n);
}This prints 255 ff true. Round-tripping through Display and FromStr works for integers. For floats, Display prints the shortest text that parses back to the same value.
Common mistakes
- Forgetting to trim input from
read_line. - Using
unwrap()on user input. Usematch,?, orunwrap_orwith a default. - Expecting
parse::<u32>()to accept-0or+-5. Only an optional leading+is allowed for unsigned types. - Assuming
boolparsing is case-insensitive. Normalize withto_lowercase()first if you need that. - Using
ascasts after parsing to a wider type. Parse directly into the type you need so range checks apply.
Exercise
What does "-1".parse::<u32>() return, and which IntErrorKind does it report?
Show answer
It returns Err(ParseIntError). The kind is InvalidDigit, because an unsigned type does not accept a leading minus sign. Only a leading + is allowed.
Exercise
Write a function parse_pair(s: &str) -> Option<(String, i32)> that parses text like "age=30" into ("age", 30), returning None on any failure.
Show answer
fn parsepair(s: &str) -> Option<(String, i32)> { let (key, value) = s.splitonce('=')?; let n = value.trim().parse::<i32>().ok()?; Some((key.trim().tostring(), n)) } The ? on splitonce returns None when there is no '=', and .ok() turns a parse error into None.
Exercise
Why does "1,5".parse::<f64>() fail, and how would you accept it?
Show answer
Float parsing always uses '.' as the decimal separator and ignores locale. To accept "1,5", replace the comma first, for example s.replace(',', ".").parse::<f64>(), after checking that the input contains only one comma.