Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Strings and Text

Rust str::parse and the FromStr trait

Reference for Rust str::parse and the FromStr trait: parsing integers, floats, bool and char, error types, turbofish, and implementing FromStr for your own types.

str::parse::<F>() turns text into a value of any type F that implements the FromStr trait. It returns a Result, because text can be invalid. The standard library implements FromStr for all integer and float types, bool, char, String, IP and socket addresses, and a few others.

The target type must be known: write it with the turbofish (s.parse::<i32>()) or let a type annotation or function signature decide it. parse is the method form of F::from_str(s).

Rust
let n: i32 = "42".parse().unwrap();
let x = "3.5".parse::<f64>();

Try it

Rust Parsing numbers and other types

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 Errors and a custom 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
fn parse<F: FromStr>(&self) -> Result<F, F::Err>

trait FromStr: Sized {
    type Err;
    fn from_str(s: &str) -> Result<Self, Self::Err>;
}
Name Description
F The target type. It must implement FromStr.
F::Err The error type of that implementation, for example ParseIntError, ParseFloatError, ParseBoolError, ParseCharError or AddrParseError.

Returns: Ok(value) when the whole string is a valid representation, otherwise Err(F::Err).

Errors / panics / edge cases: parse never panics. ParseIntError::kind() gives an IntErrorKind: Empty, InvalidDigit, PosOverflow, NegOverflow or Zero (for non-zero types).

Usage notes

  • The whole string must match. No surrounding whitespace, no trailing text. Call trim() first when reading from input.
  • Integers accept an optional sign. +5 is valid, and -1 is invalid for unsigned types (it reports InvalidDigit). There are no _ separators, no 0x prefixes and no thousands separators; use from_str_radix(s, 16) for other bases.
  • Floats accept 3.14, .5, 5., 1e3, inf, -infinity and NaN (case-insensitive for the words), with an optional sign. They do not accept hex or , as a decimal mark.
  • bool accepts only "true" and "false", exactly, in lowercase. char accepts a string of exactly one character.
  • Choose the type with the turbofish when inference has nothing else to go on: "5".parse::<u64>(). Without it you get "type annotations needed".
  • Errors implement Display and Error, so they work with ? into Box<dyn Error>.
  • Implement FromStr for your own types to get .parse() for free. Convention: parse the full text and return a descriptive error type.
  • TryFrom or From are for conversions between values, not text. FromStr is specifically text to value.