为什么要定义具有单元类型的单个私有字段的结构?

m-b*_*bat 38 rust

为什么ParseBoolError会有_priv字段:

pub struct ParseBoolError {
    _priv: (),
}
Run Code Online (Sandbox Code Playgroud)

我不认为该_priv领域被使用。

Pet*_*all 38

如果结构具有私有字段,则无法创建该结构的实例。这只是防止ParseBoolError在用户代码中构造的一个技巧。

这样做的一个原因是为了向前兼容。如果用户可以创建它:

let error = ParseBoolError {};
Run Code Online (Sandbox Code Playgroud)

那么未来版本的ParseBoolError无法在不破坏该代码的情况下添加字段。

  • 现在有一个属性也可以执行此操作:[`#[non_exhaustive]`](https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute)。`non_exhaustive` 属性阻止任何其他 crate 创建您的结构的实例,因为它将来可能会发生变化。在枚举上,它要求您始终在“match”语句中指定“_”。 (4认同)