Trait std::str::FromStr 1.0.0[−][src]
Expand description
解析字符串中的值
FromStr 的 from_str
方法通常通过 str
的 parse
方法隐式使用。
有关示例,请参见 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