[英]What's the standard way to create custom conversion between types in Rust?
If I defined some enum and wanted to create a parser from string to that type, is there something better than just: 如果我定义了一些枚举并且想要从字符串到该类型创建一个解析器,那么有什么比仅仅更好:
impl TheType {
fn from_str(s: &str) -> TheType {
// ...
}
}
The right way for converting from a string / parsing text is to implement the FromStr
trait. 从字符串/解析文本转换的正确方法是实现
FromStr
特征。 For the example from the question it would look like this: 对于问题中的示例,它看起来像这样:
use std::str::FromStr;
enum Failure {
ReasonOne,
ReasonTwo,
}
impl FromStr for TheType {
type Err = Failure;
fn from_str(s: &str) -> Result<TheType, Self::Err> {
unimplemented!()
}
}
For generic conversion that cannot fail, you should implement the std::convert::From
trait: 对于不能失败的泛型转换,您应该实现
std::convert::From
trait:
use std::convert::From;
#[derive(PartialEq, Eq, Debug)]
enum MyEnum {
One,
Two,
Many(i64),
}
impl From<i64> for MyEnum {
fn from(val: i64) -> Self {
match val {
1 => MyEnum::One,
2 => MyEnum::Two,
_ => MyEnum::Many(val),
}
}
}
fn main() {
assert_eq!(MyEnum::from(1), MyEnum::One);
assert_eq!(MyEnum::from(2), MyEnum::Two);
assert_eq!(MyEnum::from(3), MyEnum::Many(3));
}
Conveniently, implementing From
also automatically implements Into
: 方便的是,实现
From
也自动实现Into
:
let one: MyEnum = 1.into(); assert_eq!(one, MyEnum::One);
let two: MyEnum = 2.into(); assert_eq!(two, MyEnum::Two);
let many: MyEnum = 3.into(); assert_eq!(many, MyEnum::Many(3));
For potentially failing conversion, you should implement std::convert::TryFrom
instead. 对于可能失败的转换,您应该实现
std::convert::TryFrom
。 It's only available in Rust 1.34 and up though, before these versions you can use the implementation in the conv
crate . 它仅在Rust 1.34及更高版本中可用,在这些版本之前,您可以在
conv
使用该实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.