gpt4 book ai didi

rust - 创建一个无法在其 crate 之外实例化的零大小结构的惯用方法是什么?

转载 作者:行者123 更新时间:2023-12-03 11:23:52 24 4
gpt4 key购买 nike

我有类似的东西:

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不需要存储任何内部状态来做我想做的事情(它只是用作枚举中的占位符),所以我把它做成了一个零大小的结构。但是,将来可能会改变,所以我想阻止这个 crate 之外的代码实例化 A不经过 A::new() (即, obj2 中的 main() 的实例化应该失败)。
本质上,我想要的效果就像我在 A 中添加了一个私有(private)字段一样。 ,但我希望它保持零大小。
目前,我正在考虑这样的事情:
pub struct A {
empty: (),
}
或这个:
pub struct A(());
但是,我不确定哪种方式最惯用。

最佳答案

对此没有既定的成语。我会使用元组结构版本:

pub struct A(());
由于该字段是私有(private)的,因此该模块之外的任何人都无法构造 A .
这是使用 inside the standard library :
pub struct Stdin(());
pub struct Stdout(());
pub struct Stderr(());
标准库 also uses the named field version :
pub struct Empty {
_priv: (),
}
您可以使用任何大小为零的类型(例如零长度数组或 PhantomData ),但 ()是最简单的。
也可以看看:
  • Why define a struct with single private field of unit type?
  • What's the Rust idiom to define a field pointing to a C opaque pointer?
  • What are the differences between the multiple ways to create zero-sized structs?
  • 关于rust - 创建一个无法在其 crate 之外实例化的零大小结构的惯用方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64651511/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com