【发布时间】:2021-01-18 17:06:08
【问题描述】:
许多结构需要强制使用构造函数来创建对象,但我希望拥有对所有字段的公共读取访问权限。
我需要使用bish.bash.bosh.wibble.wobble 访问多个深度级别 - 出于可读性和可能的性能原因,bish.get_bash().get_bosh().get_wibble().get_wobble() 不是我想去的地方。
我正在使用这个可怕的杂物:
#[derive(Debug)]
pub struct Foo {
pub bar: u8,
pub baz: u16,
dummy: bool,
}
impl Foo {
pub fn new(bar: u8, baz: u16) -> Foo {
Foo {bar, baz, dummy: true}
}
}
这显然是在浪费少量空间,dummy 在其他地方造成不便。
我应该怎么做?
【问题讨论】:
-
这能回答你的问题吗? How to restrict the construction of struct?
-
TL;Dr 使用
()而不是bool因为单位类型是零大小类型 (ZST) -
@hellow 谢谢,问题不一样,但该答案的最后一部分是适用的。使用
_private: ()仍然需要我在序列化期间处理它的存在 - 但我可以在serde中解决这个问题。