我发现这个很棒 blog post关于 Rust 中的错误处理。
它定义了一个错误结构:
struct ProgramError {
kind: ProgramErrorKind,
message: SendStr
}
对于消息,它使用 SendStr
这是 MaybeOwned<'static>
的类型别名.我知道这可以容纳 &str
或 String
但文档对其用例有点含糊。
This can be useful as an optimization when an allocation is sometimes needed but not always.
我想明白为什么要选择SendStr
在 &str
或 String
在定义 ProgramError
的情况下类。
最佳答案
SendStr
是 String
或 &'static str
,允许它在使用字符串文字的常见情况下高效(不需要每次分配一个新值),同时在必要时能够使用动态值。
为什么不一直使用&str
?好吧,要么你只需要将它设为静态字符串,要么用户需要在动态值的情况下将字符串存储在其他地方,因此传递错误(最值得注意的是,向上堆栈)将更加困难.
关于string - 为什么我应该使用 SendStr(通过 &str 或 String)作为 Rust 中 Error 结构的消息属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25149078/