Skip to content
Tutorials Center
My learning

Topics

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.

Rust
let n: u16 = "8080".parse().unwrap();
let p = "3,4".parse::<Point>();

Try it

Rust Standard parsing and errors

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.

Rust Implementing FromStr

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

Rust
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

  • parse needs 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. Call trim() first, especially for input read from stdin.
  • Integer rules: an optional leading + is accepted (and - for signed types), no underscores, no 0x prefix (use from_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.
  • bool accepts only "true" and "false"; char requires exactly one character.
  • Errors: make the Err type implement Display and std::error::Error, and convert inner errors with From so ? works inside from_str.
  • Collecting: iter.map(str::parse::<T>).collect::<Result<Vec<_>, _>>() returns the first error or all values.
  • Not for lifetimes. FromStr cannot return values borrowing from s, because the trait has no lifetime parameter. For zero-copy parsers write an ordinary function or use TryFrom<&str>.
  • Round trips: if you implement Display, make from_str(&x.to_string()) give x back whenever possible.