如果我定义了一些枚举并想创建一个从字符串到该类型的解析器,有没有比这更好的东西:
impl TheType {
fn from_str(s: &str) -> TheType {
// ...
}
}
最佳答案
从字符串转换/解析文本的正确方法是实现 FromStr
特征。对于问题中的示例,它看起来像这样:
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!()
}
}
关于type-conversion - 在 Rust 中创建类型之间的自定义转换的标准方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15041794/