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

1.6k views Asked by At

Many structs need to enforce the use of a constructor for object creation, but I want to have public read access to all of the fields.

I need to access several levels deep with bish.bash.bosh.wibble.wobble - bish.get_bash().get_bosh().get_wibble().get_wobble() is not somewhere I want to go, for readability and possibly performance reasons.

This horrible kludge is what I'm using:

#[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}
    }
}

This is obviously wasting a small amount of space, and dummy is causing inconvenience elsewhere.

How should I do this?

1

There are 1 answers

0
fadedbee On BEST ANSWER

Thanks to @hellow I now have a working solution:

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