【问题标题】:How can I make all the fields of structs publicly readable while enforcing the use of a "new" constructor如何在强制使用“新”构造函数的同时使结构的所有字段公开可读
【发布时间】: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 中解决这个问题。

标签: struct rust public serde


【解决方案1】:

感谢@hellow,我现在有了一个可行的解决方案:

use serde::{Serialize, Deserialize}; // 1.0.115

#[derive(Serialize, Deserialize, Debug)]
pub struct Foo {
    pub bar: u8,
    pub baz: u16,

    #[serde(skip)] 
    _private: (),
}

impl Foo {
    pub fn new(bar: u8, baz: u16) -> Foo {
        Foo {bar, baz, _private: ()}
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 2020-04-03
    • 1970-01-01
    • 2020-08-13
    • 2021-09-21
    • 2017-04-30
    • 2020-08-17
    相关资源
    最近更新 更多