在强制使用 "new" 构造函数的同时,如何使结构的所有字段公开可读

How can I make all the fields of structs publicly readable while enforcing the use of a "new" constructor

许多结构需要强制使用构造函数来创建对象,但我想要 public 读取所有字段的权限。

我需要使用 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}
    }
}

这显然是在浪费少量space,而且dummy在其他地方造成不便。

我应该怎么做?

感谢@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: ()}
    }
}