Why define a struct with single private field of unit type?

浪子不回头ぞ 提交于 2020-08-26 14:01:23

问题


I do not know why struct ParseBoolError has the _priv field, as shown below:

pub struct ParseBoolError {
    _priv: (),
}

https://doc.rust-lang.org/src/core/str/mod.rs.html#150

I think that the _priv field is not used.


回答1:


You can't create an instance of a struct if it has private fields. This is just a trick to prevent ParseBoolError from being constructed in user code.

One reason to do this is for forwards compatibility. If users could create it with:

let error = ParseBoolError {};

then a future version of ParseBoolError couldn't add fields without breaking that code.



来源:https://stackoverflow.com/questions/63338208/why-define-a-struct-with-single-private-field-of-unit-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!