如何将 to_string() 功能添加到枚举中?

How can I add the to_string() functionality to an enum?

我正在尝试创建实现 to_string()Error 枚举。我已经尝试为他们derive(Debug),但似乎还不够。

这是我正在处理的枚举:

#[derive(Debug, Clone)]
pub enum InnerError {
    InnerErrorWithDescription(String),
}

#[derive(Debug, Clone)]
pub enum OuterError {
    OuterErrorWithDescription(String),
}

我想做的是:

// result type <T,InnerErrorWithDescription>
result.map_err(|err| { Error::OuterErrorWithDescription(err.to_string())}) // .to_string() is not available

我无法将 InnerError 枚举类型转换为 OuterError

我应该改变什么来实现它?

我在这里做了一个编写枚举类型及其值的示例:

Rust Playground

但是,我仍然必须在匹配案例中指定类型和描述,是否有更通用的实现?

您的枚举应该实现 Display; from ToString 文档:

This trait is automatically implemented for any type which implements the Display trait. As such, ToString shouldn't be implemented directly: Display should be implemented instead, and you get the ToString implementation for free.

编辑:我已经调整了你的游乐场示例;我想你可能在追求某些东西 like this.