pub trait FromStr: Sized {
type Err;
// Required method
fn from_str(s: &str) -> Result<Self, Self::Err>;
}
Parse a value from a string
FromStr’s from_str method is often used implicitly, through str’s parse method. See parse’s documentation for examples.
FromStr does not have a lifetime parameter, and so you can only parse types that do not contain a lifetime parameter themselves. In other words, you can parse an i32 with FromStr, but not a &i32. You can parse a struct that contains an i32, but not one that contains an &i32.
The input format expected by a type’s FromStr implementation depends on the type. Check the type’s documentation for the input formats it knows how to parse. Note that the input format of a type’s FromStr implementation might not necessarily accept the output format of its Display implementation, and even if it does, the Display implementation may not be lossless so the round-trip may lose information.
However, if a type has a lossless Display implementation whose output is meant to be conveniently machine-parseable and not just meant for human consumption, then the type may wish to accept the same format in FromStr, and document that usage. Having both Display and FromStr implementations where the result of Display cannot be parsed with FromStr may surprise users.
Basic implementation of FromStr on an example Point type:
use std::str::FromStr;
#[derive(Debug, PartialEq)]
struct Point {
x: i32,
y: i32
}
#[derive(Debug, PartialEq, Eq)]
struct ParsePointError;
impl FromStr for Point {
type Err = ParsePointError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (x, y) = s
.strip_prefix('(')
.and_then(|s| s.strip_suffix(')'))
.and_then(|s| s.split_once(','))
.ok_or(ParsePointError)?;
let x_fromstr = x.parse::<i32>().map_err(|_| ParsePointError)?;
let y_fromstr = y.parse::<i32>().map_err(|_| ParsePointError)?;
Ok(Point { x: x_fromstr, y: y_fromstr })
}
}
let expected = Ok(Point { x: 1, y: 2 });
// Explicit call
assert_eq!(Point::from_str("(1,2)"), expected);
// Implicit calls, through parse
assert_eq!("(1,2)".parse(), expected);
assert_eq!("(1,2)".parse::<Point>(), expected);
// Invalid input string
assert!(Point::from_str("(1 2)").is_err());type Err
The associated error which can be returned from parsing.
fn from_str(s: &str) -> Result<Self, Self::Err>
Parses a string s to return a value of this type.
If parsing succeeds, return the value inside Ok, otherwise when the string is ill-formatted return an error specific to the inside Err. The error type is specific to the implementation of the trait.
Basic usage with i32, a type that implements FromStr:
use std::str::FromStr; let s = "5"; let x = i32::from_str(s).unwrap(); assert_eq!(5, x);
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
impl FromStr for IpAddr
type Err = AddrParseError
impl FromStr for SocketAddr
type Err = AddrParseError
impl FromStr for bool
type Err = ParseBoolError
impl FromStr for char
type Err = ParseCharError
impl FromStr for f16
type Err = ParseFloatError
impl FromStr for f32
type Err = ParseFloatError
impl FromStr for f64
type Err = ParseFloatError
impl FromStr for i8
type Err = ParseIntError
impl FromStr for i16
type Err = ParseIntError
impl FromStr for i32
type Err = ParseIntError
impl FromStr for i64
type Err = ParseIntError
impl FromStr for i128
type Err = ParseIntError
impl FromStr for isize
type Err = ParseIntError
impl FromStr for u8
type Err = ParseIntError
impl FromStr for u16
type Err = ParseIntError
impl FromStr for u32
type Err = ParseIntError
impl FromStr for u64
type Err = ParseIntError
impl FromStr for u128
type Err = ParseIntError
impl FromStr for usize
type Err = ParseIntError
impl FromStr for ByteString
type Err = Infallible
impl FromStr for CString
type Err = NulError
impl FromStr for OsString
type Err = Infallible
impl FromStr for Ipv4Addr
type Err = AddrParseError
impl FromStr for Ipv6Addr
type Err = AddrParseError
impl FromStr for SocketAddrV4
type Err = AddrParseError
impl FromStr for SocketAddrV6
type Err = AddrParseError
impl FromStr for NonZero<i8>
type Err = ParseIntError
impl FromStr for NonZero<i16>
type Err = ParseIntError
impl FromStr for NonZero<i32>
type Err = ParseIntError
impl FromStr for NonZero<i64>
type Err = ParseIntError
impl FromStr for NonZero<i128>
type Err = ParseIntError
impl FromStr for NonZero<isize>
type Err = ParseIntError
impl FromStr for NonZero<u8>
type Err = ParseIntError
impl FromStr for NonZero<u16>
type Err = ParseIntError
impl FromStr for NonZero<u32>
type Err = ParseIntError
impl FromStr for NonZero<u64>
type Err = ParseIntError
impl FromStr for NonZero<u128>
type Err = ParseIntError
impl FromStr for NonZero<usize>
type Err = ParseIntError
impl FromStr for PathBuf
type Err = Infallible
impl FromStr for String
type Err = Infallible
© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/str/trait.FromStr.html