动态生成字符串时如何返回&str?

fad*_*bee 2 rust

我的虚拟机出现以下错误代码:

/// These are the different types of errors which stepping through a VM can produce.
#[derive(Debug, PartialEq)]
enum VmErrorType {
    UnknownOpCode(i8),
    UnknownVariable(char),
    IllegalVariableName(i8),
    IllegalJump(i8, usize, usize),
    StackEmpty,
    UnexpectedEndOfBytecode,
}

/// VmError encapsulates the VmErrorType and adds the common offset of where the error was found.
#[derive(Debug, PartialEq)]
pub struct VmError { // public so that errors can be interrogated
    subtype: VmErrorType, // "type" is a reserved keyword
    offset: usize,
}

impl fmt::Display for VmError {
    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        let message = match self.subtype {
            VmErrorType::UnknownOpCode(opcode) => format!("unknown opcode ({opcode})"),
            VmErrorType::UnknownVariable(varname) => format!("unknown variable ({varname})"),
            VmErrorType::IllegalVariableName(varname) => format!("illegal variable name ({varname})"),
            VmErrorType::IllegalJump(delta, src, dst) => format!("illegal jump of {delta} from {src} to {dst}"),
            VmErrorType::StackEmpty => "empty stack".to_string(),
            VmErrorType::UnexpectedEndOfBytecode => "unexpected end of bytecode".to_string(),
        };
        write!(f, "{} at offset {}", message, self.offset)
    }
}

impl error::Error for VmError {
    fn description(&self) -> &str {
        "VmError" // FIXME: this could do with being more specific, but we have lifetime issues here
    }
}
Run Code Online (Sandbox Code Playgroud)

当它们动态生成时,如何将 adescription()作为 an返回?&str

是否有更好的方法来构造多个错误情况,其中某些属性是特定于错误的,而其他属性 ( offset) 适用于所有错误?

Col*_*Two 5

这是 的已知缺陷Error::description(),这就是为什么它被弃用并且您不应该使用它。

相反,请std::fmt::Display针对您的错误类型实施。不用费心实施description;假装它不存在。