Reputation: 44797
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?
Upvotes: 3
Views: 2042
Reputation: 44797
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: ()}
}
}
Upvotes: 5