Rust Reference ยท Core Traits
The FromStr trait
Reference for the Rust FromStr trait: how str::parse works, implementing FromStr for your own types, error types, and what standard parsers accept.
FromStr defines how a type is built from a string slice. Its method from_str returns a Result, and the familiar "42".parse::<i32>() is just i32::from_str("42") in disguise: str::parse is generic over any F: FromStr.
The standard library implements it for numbers, bool, char, String, network addresses and a few more. You implement it for your own types, such as a point, a color or a command, and then everything that parses text (parse, clap-style argument parsing, config readers) works with them.
let n: u16 = "8080".parse().unwrap(); let p = "3,4".parse::<Point>();
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait FromStr: Sized { type Err; fn from_str(s: &str) -> Result<Self, Self::Err>; } impl str { pub fn parse<F: FromStr>(&self) -> Result<F, F::Err>; }
| Name | Description |
|---|---|
s |
The text to parse. It is borrowed; the result must not hold on to it (use String for text fields). |
Err |
The error type. Integers use ParseIntError, floats ParseFloatError, bool ParseBoolError, char ParseCharError. |
Returns: Ok(value) or Err(error). The function does not panic for bad input.
Usage notes
parseneeds the target type, either by annotation (let n: i32 = s.parse()?) or turbofish (s.parse::<i32>()).- No trimming.
" 5"and"5\n"are errors for numbers. Calltrim()first, especially for input read from stdin. - Integer rules: an optional leading
+is accepted (and-for signed types), no underscores, no0xprefix (usefrom_str_radix), and overflow is reported as an error, not wrapped. Unsigned types reject any leading-. - Float rules:
"1e3",".5","5.","inf","-infinity"and"NaN"are accepted (case-insensitive for the words);"1,5"is not. boolaccepts only"true"and"false";charrequires exactly one character.- Errors: make the
Errtype implementDisplayandstd::error::Error, and convert inner errors withFromso?works insidefrom_str. - Collecting:
iter.map(str::parse::<T>).collect::<Result<Vec<_>, _>>()returns the first error or all values. - Not for lifetimes.
FromStrcannot return values borrowing froms, because the trait has no lifetime parameter. For zero-copy parsers write an ordinary function or useTryFrom<&str>. - Round trips: if you implement
Display, makefrom_str(&x.to_string())givexback whenever possible.