Trait std::str::FromStr1.0.0[][src]

pub trait FromStr {
    type Err;
    fn from_str(s: &str) -> Result<Self, Self::Err>;
}
Expand description

解析字符串中的值

FromStr 的 from_str 方法通常通过 strparse 方法隐式使用。 有关示例,请参见 parse 的文档。

FromStr 没有生命周期参数,因此您只能解析本身不包含生命周期参数的类型。

换句话说,您可以使用 FromStr 解析 i32,但是不能解析 &i32。 您可以解析包含 i32 的结构体,但不能解析包含 &i32 的结构体。

Examples

FromStr 在示例 Point 类型上的基本实现:

use std::str::FromStr;
use std::num::ParseIntError;

#[derive(Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32
}

impl FromStr for Point {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
                                 .split(',')
                                 .collect();

        let x_fromstr = coords[0].parse::<i32>()?;
        let y_fromstr = coords[1].parse::<i32>()?;

        Ok(Point { x: x_fromstr, y: y_fromstr })
    }
}

let p = Point::from_str("(1,2)");
assert_eq!(p.unwrap(), Point{ x: 1, y: 2} )
Run

Associated Types

可以从解析中返回的相关错误。

Required methods

解析字符串 s 以返回此类型的值。

如果解析成功,则返回 Ok 内部的值,否则,当字符串格式错误时,返回特定于 Err 内部的错误。 错误类型特定于 trait 的实现。

Examples

i32 的基本用法,一种实现 FromStr 的类型:

use std::str::FromStr;

let s = "5";
let x = i32::from_str(s).unwrap();

assert_eq!(5, x);
Run

Implementors