pub trait FromStr: Sized {
    type Err;
    // Required method
    fn from_str(s: &str) -> Result<Self, Self::Err>;
}Expand description
解析字符串中的值
FromStr 的 from_str 方法通常通过 str 的 parse 方法隐式使用。
有关示例,请参见 parse 的文档。
FromStr 没有生命周期参数,因此您只能解析本身不包含生命周期参数的类型。
换句话说,您可以使用 FromStr 解析 i32,但是不能解析 &i32。
您可以解析包含 i32 的结构体,但不能解析包含 &i32 的结构体。
Examples
FromStr 在示例 Point 类型上的基本实现:
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 });
// 显式调用
assert_eq!(Point::from_str("(1,2)"), expected);
// 隐式调用,通过解析
assert_eq!("(1,2)".parse(), expected);
assert_eq!("(1,2)".parse::<Point>(), expected);
// 输入字符串无效
assert!(Point::from_str("(1 2)").is_err());Run