Sub topic 11
Parsing strings into other types
This chapter assumes you know ownership and borrowing basics, Option and Result, and how to slice a &str. You have already seen how to search and split text. Now you turn the pieces into typed values.
The FromStr trait and parse
The standard library converts text into values through the FromStr trait. You rarely call it directly. Instead you call str::parse, which picks the implementation from the target type.
fn main() {
let a = "42".parse::<i32>();
let b: Result<f64, _> = "3.5".parse();
let c = "true".parse::<bool>();
println!("{:?} {:?} {:?}", a, b, c);
}parse returns a Result, because the text may not be valid for the type. The compiler must know the target type. You supply it with a turbofish (parse::<i32>()) or with a type annotation on the binding.
Splitting, then parsing
Parsing usually follows a split. This example reads a key=value line and converts the value.
fn parse_setting(line: &str) -> Option<(&str, u16)> {
let (key, value) = line.split_once('=')?;
let port = value.trim().parse::<u16>().ok()?;
Some((key.trim(), port))
}
fn main() {
println!("{:?}", parse_setting("port = 8080"));
println!("{:?}", parse_setting("port = abc"));
println!("{:?}", parse_setting("no separator"));
}The ? operator returns None early when split_once finds no separator. The .ok() call turns the parse Result into an Option and discards the error detail. Keep the error instead when the caller needs to report why parsing failed.
Common errors
Each numeric type has its own error type, such as ParseIntError. Its kind() method tells you the cause.
use std::num::IntErrorKind;
fn main() {
for text in ["", "12x", "300", " 7"] {
match text.parse::<u8>() {
Ok(n) => println!("{text:?} -> {n}"),
Err(e) => match e.kind() {
IntErrorKind::Empty => println!("{text:?} is empty"),
IntErrorKind::InvalidDigit => println!("{text:?} has a bad digit"),
IntErrorKind::PosOverflow => println!("{text:?} is too large"),
_ => println!("{text:?} failed: {e}"),
},
}
}
}Three mistakes come up often:
- Whitespace.
" 7".parse::<u8>()fails withInvalidDigit. Calltrim()first. - Overflow.
"300"does not fit inu8. The parse fails instead of wrapping. - Sign and format rules.
"+5"parses as an integer, but"5."and"1,000"do not. A float accepts forms like"1e3"and"inf".
Propagating errors with ?
Inside a function that returns a Result, the ? operator passes the parse error to the caller. A Box<dyn Error> return type accepts many error types.
use std::error::Error;
fn sum(text: &str) -> Result<i32, Box<dyn Error>> {
let mut total = 0;
for part in text.split(',') {
total += part.trim().parse::<i32>()?;
}
Ok(total)
}
fn main() {
println!("{:?}", sum("1, 2, 3").ok());
match sum("1, two, 3") {
Ok(n) => println!("sum = {n}"),
Err(e) => println!("error: {e}"),
}
}Because ? converts the error through From, the same function could also return other error types.
Implementing FromStr for your own type
Implement FromStr and your type gets parse for free.
use std::str::FromStr;
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
impl FromStr for Point {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (x, y) = s.split_once(',').ok_or("missing comma")?;
let x = x.trim().parse().map_err(|_| "bad x")?;
let y = y.trim().parse().map_err(|_| "bad y")?;
Ok(Point { x, y })
}
}
fn main() {
println!("{:?}", "3, 4".parse::<Point>());
println!("{:?}", "3;4".parse::<Point>());
}A String error is fine for a small example. In a library, define a dedicated error type.
Going the other way
Converting a value to text uses to_string(), which works for any type that implements Display. It is the counterpart of parse for most round trips.
Exercise
Why does " 12".parse::<i32>() return an error, and what is the smallest change that makes it succeed?
Show answer
parse does not skip whitespace, so the leading spaces cause an InvalidDigit error. Calling trim() first, as in " 12".trim().parse::<i32>(), fixes it.
Exercise
What two things can you write so that let n = "9".parse().unwrap(); compiles when nothing else tells the compiler the type?
Show answer
Annotate the binding (let n: i32 = ...) or use the turbofish ("9".parse::<i32>()). parse needs a target type to choose a FromStr implementation.