Trait alloc::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} )
RunAssociated Types
Required methods
Implementations on Foreign Types
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
从字符串中解析 bool
。
产生 Result<bool, ParseBoolError>
,因为 s
实际上可以解析,也可以不解析。
Examples
use std::str::FromStr;
assert_eq!(FromStr::from_str("true"), Ok(true));
assert_eq!(FromStr::from_str("false"), Ok(false));
assert!(<bool as FromStr>::from_str("not even a boolean").is_err());
Run注意,在许多情况下,str
上的 .parse()
方法更合适。
assert_eq!("true".parse(), Ok(true));
assert_eq!("false".parse(), Ok(false));
assert!("not even a boolean".parse::<bool>().is_err());
Runtype Err = ParseBoolError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
将以 10 为底的字符串转换为浮点数。 接受可选的十进制指数。
该函数接受诸如以下的字符串
- ‘3.14’
- ‘-3.14’
- ‘2.5E10’,或等效的 ‘2.5e10’
- ‘2.5E-10’
- ‘5.’
- ‘.5’,或等效地,‘0.5’
- ‘inf’, ‘-inf’, ‘NaN’
前导和尾随空格表示错误。
Grammar
Float ::= Sign? ( 'inf' | 'NaN' | Number )
Number ::= ( Digit+ |
Digit+ '.' Digit* |
Digit* '.' Digit+ ) Exp?
Exp ::= [eE] Sign? Digit+
Sign ::= [+-]
Digit ::= [0-9]
Arguments
- src - 字符串
返回值
Err(ParseFloatError)
如果字符串不代表有效数字。
否则,为 Ok(n)
,其中 n
是 src
表示的浮点数。
type Err = ParseFloatError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
type Err = ParseIntError
将以 10 为底的字符串转换为浮点数。 接受可选的十进制指数。
该函数接受诸如以下的字符串
- ‘3.14’
- ‘-3.14’
- ‘2.5E10’,或等效的 ‘2.5e10’
- ‘2.5E-10’
- ‘5.’
- ‘.5’,或等效地,‘0.5’
- ‘inf’, ‘-inf’, ‘NaN’
前导和尾随空格表示错误。
Grammar
Float ::= Sign? ( 'inf' | 'NaN' | Number )
Number ::= ( Digit+ |
Digit+ '.' Digit* |
Digit* '.' Digit+ ) Exp?
Exp ::= [eE] Sign? Digit+
Sign ::= [+-]
Digit ::= [0-9]
Arguments
- src - 字符串
返回值
Err(ParseFloatError)
如果字符串不代表有效数字。
否则,为 Ok(n)
,其中 n
是 src
表示的浮点数。