I have a Foo structure that represents an external serialization format. Foo has dozens of fields, and they are all added all the time. Fortunately, all new fields are guaranteed to have reasonable default values.
Rust has good syntax for creating a structure using default values, and then updating a few selected values:
Foo { bar: true, ..Default::default() }
Similarly, we can present the idea “this structure may have more fields in a future version” using a private field of the PhantomData type.
But if we combine these two idioms, we get an error:
use std::default::Default; mod F { use std::default::Default; use std::marker::PhantomData; pub struct Foo { pub bar: bool, phantom: PhantomData<()>, } impl Default for Foo { fn default() -> Foo { Foo { bar: false, phantom: PhantomData, } } } } fn main() { F::Foo { bar: true, ..Default::default() }; }
This gives us an error:
error: field `phantom` of struct `F::Foo` is private [--explain E0451] --> <anon>:23:5 |> 23 |> F::Foo { |> ^
Logically, I would say that this should work, because we are only updating public fields, and that would be a useful idiom. An alternative is to support something like:
Foo::new() .set_bar(true)
... which will be tedious with dozens of fields.
How can I get around this problem?
struct rust
emk
source share