gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:47:47 25 4
gpt4 key购买 nike

我正在尝试创建实现 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 ;来自 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.

编辑:我已经调整了你的 Playground 示例;我想你可能在追求什么like this .

关于string - 如何将 to_string() 功能添加到枚举中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52720831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com