实现 TryFrom 我应该使用 &str 还是 String

Dar*_*ria 6 rust

我有一个类型Instruction并且会使用std::convert::TryFrom从字符串进行转换。

我应该实施 overString或 吗&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);
}
Run Code Online (Sandbox Code Playgroud)

我读了这个答案:Should Rustimplements of From/TryFrom targetreferences or values? 但我想知道最好的选择是什么:两者都实施?使用impl高级打字?

Nov*_*zen -2

*** 这实际上并不像 SirDarius 在下面指出的那样起作用。

使用T: AsRef<str>

impl<T: AsRef<str>> std::convert::TryFrom<T> for Instruction {
    type Error = InstructionParseError;    
    fn try_from(input: T) -> Result<Self, Self::Error> {
      let input: &str = input.as_ref();
      match input {
        "F" => Ok(Instruction::Forward),
        _ => unimplemented!(), // For brievity
     }
    }
}
Run Code Online (Sandbox Code Playgroud)