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).
let n: i32 = "42".parse().unwrap(); let x = "3.5".parse::<f64>();
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
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.
+5is valid, and-1is invalid for unsigned types (it reportsInvalidDigit). There are no_separators, no0xprefixes and no thousands separators; usefrom_str_radix(s, 16)for other bases. - Floats accept
3.14,.5,5.,1e3,inf,-infinityandNaN(case-insensitive for the words), with an optional sign. They do not accept hex or,as a decimal mark. boolaccepts only"true"and"false", exactly, in lowercase.characcepts 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
DisplayandError, so they work with?intoBox<dyn Error>. - Implement
FromStrfor your own types to get.parse()for free. Convention: parse the full text and return a descriptive error type. TryFromorFromare for conversions between values, not text.FromStris specifically text to value.
Related
trim,split_once,Result,charmethods- Lessons: Strings, Strings overview