I have a type Instruction
and would use std::convert::TryFrom
to convert from a string.
Shall I implement over String
or &str
? If I use &str
I am obliged to
use &*
pattern or as_ref()
.
I have something like: Rust Playground permalink
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);
}
I read this answer: Should Rust implementations of From/TryFrom target references or values? but i am wondering what is the best option: Implement both? Use impl
avanced typing?