创建无法在其板条箱外部实例化的零大小结构的惯用方式是什么? [英] What is an idiomatic way to create a zero-sized struct that can't be instantiated outside its crate?

查看:50
本文介绍了创建无法在其板条箱外部实例化的零大小结构的惯用方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的东西:

mod private {
    // My crate
    pub struct A;
    
    impl A {
        pub fn new() -> Self {
            Self
        }
        // ...
    }
}

fn main() {
    // External code
    let obj = private::A::new();
    let obj2 = private::A;
}

当前, A 不需要存储任何内部状态即可执行我想要的操作(它只是在枚举中用作占位符),因此我将其设置为零大小结构.但是,将来可能会发生变化,因此我想防止此板条箱外的代码实例化 A 而不进行 A :: new()(即< main()中的code> obj2 应该会失败).

Currently, A doesn't need to store any internal state to do what I want it to (it's just being used as a placeholder in an enum), so I made it a zero-sized struct. However, that might change in the future, so I want to prevent code outside this crate from instantiating A without going through A::new() (i.e. the instantiation of obj2 in main() as it stands should fail).

本质上,我希望获得与向 A 添加一个私有字段一样的效果,但是我希望它保持零大小.

Essentially, I want the same effect as if I'd added a private field to A, but I want it to remain zero-sized.

目前,我正在考虑类似这样的事情:

Currently, I'm thinking about something like this:

pub struct A {
    empty: (),
}

或者这个:

pub struct A(());

但是,我不确定哪种方法最惯用.

However, I'm not sure which way is most idiomatic.

推荐答案

没有为此建立的惯用语.我会使用元组struct版本:

There is no established idiom for this. I'd use the tuple struct version:

pub struct A(());

由于该字段是私有字段,因此该模块之外的任何人都无法构造 A .

Since the field is private, no one outside that module can construct A.

这用于在标准库中:

pub struct Stdin(());
pub struct Stdout(());
pub struct Stderr(());

标准库

The standard library also uses the named field version:

pub struct Empty {
    _priv: (),
}

您可以使用任何零大小的类型(例如,零长度数组或

You could use any zero-sized type (e.g. a zero-length array or PhantomData), but () is the simplest.

另请参阅:

这篇关于创建无法在其板条箱外部实例化的零大小结构的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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