为什么要定义具有单元类型的单个私有字段的结构? [英] Why define a struct with single private field of unit type?

查看:43
本文介绍了为什么要定义具有单元类型的单个私有字段的结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 ParseBoolError_priv 字段:

pub struct ParseBoolError {
    _priv: (),
}

我认为没有使用 _priv 字段.

I don't think that the _priv field is used.

推荐答案

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

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 {};

然后 ParseBoolError 的未来版本无法在不破坏代码的情况下添加字段.

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

这篇关于为什么要定义具有单元类型的单个私有字段的结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆