本文簡要介紹rust語言中 Trait core::str::FromStr 的用法。
用法
pub trait FromStr: Sized {
type Err;
fn from_str(s: &str) -> Result<Self, Self::Err>;
}從字符串中解析一個值
FromStr 的 from_str 方法經常被隱式使用,通過 str 的 parse 方法。有關示例,請參閱 parse 的文檔。
FromStr 沒有生命周期參數,因此您隻能解析本身不包含生命周期參數的類型。換句話說,您可以使用 FromStr 解析 i32 ,但不能解析 &i32 。您可以解析包含 i32 的結構,但不能解析包含 &i32 的結構。
例子
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} )相關用法
- Rust FromStr.from_str用法及代碼示例
- Rust FromStr用法及代碼示例
- Rust FromSecsError用法及代碼示例
- Rust FromUtf16Error用法及代碼示例
- Rust FromUtf8Error.as_bytes用法及代碼示例
- Rust FromVecWithNulError.into_bytes用法及代碼示例
- Rust FromBytesWithNulError用法及代碼示例
- Rust FromResidual.from_residual用法及代碼示例
- Rust From用法及代碼示例
- Rust FromUtf8Error.into_bytes用法及代碼示例
- Rust FromUtf8Error用法及代碼示例
- Rust FromUtf8Error.utf8_error用法及代碼示例
- Rust FromVecWithNulError用法及代碼示例
- Rust FromRawFd.from_raw_fd用法及代碼示例
- Rust FromIterator用法及代碼示例
- Rust FromVecWithNulError.as_bytes用法及代碼示例
- Rust FromIterator.from_iter用法及代碼示例
- Rust Formatter.precision用法及代碼示例
- Rust Formatter.debug_list用法及代碼示例
- Rust Formatter.sign_minus用法及代碼示例
- Rust File用法及代碼示例
- Rust FileExt.read_exact_at用法及代碼示例
- Rust FileTypeExt.is_char_device用法及代碼示例
- Rust File.open用法及代碼示例
- Rust File.sync_data用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Trait core::str::FromStr。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
