我有一个类型Instruction
,想使用std::convert::TryFrom
从字符串转换。
我应该在String
上实现还是&str
?如果我使用&str
,我必须使用&*
模式或as_ref()
。
我有类似这样的东西:Rust Playground永久链接
use std::convert::TryFrom;
enum Instruction {
Forward, /* other removed for brievity */
}
#[derive(Debug)]
struct InstructionParseError(char);
impl std::convert::TryFrom<&str> for Instruction {
type Error = InstructionParseError;
fn try_from(input: &str) -> Result<Self, Self::Error> {
match input {
"F" => Ok(Instruction::Forward),
_ => unimplemented!(), // For brievity
}
}
}
fn main() {
// I use a string because this input can come from stdio.
let instr = String::from("F");
let instr = Instruction::try_from(&*instr);
}
我阅读了这篇回答:Should Rust implementations of From/TryFrom target references or values?,但我想知道最佳选择是什么:实现两者?使用impl
高级类型?
&str
实现它,但是你可以为&String
添加一个impl,但这并不是非常重要的。你的类型可以从&str
构造,除了String
之外的任何结构体都可以有一个字符串表示形式,并且你不能为每种类型都实现TryFrom,让用户将转换为字符串应该没问题。 - Stargateur