Usually I would just follow the Struct { field1, field2, field3, ..Default::default() }
pattern, but now I have a struct where some of the fields are of a type that does not implement Default
.
What's a good way to allow constructing the struct without having to specify all the fields? The two approaches I could think of are:
-
Use two separate structs for the required and optional fields, and add a method to one or both that takes in the other and produces a merged
Struct
, e.g.StructBuilder{field1, field2}.build(StructOptional{field3, ..Default::default()})
-
Add a constructor function that takes in the required arguments, and then just set the other fields on the result, e.g.
let mut s = Struct::new(field1, field2); s.field3 = field3;
.
I don't particularly like either approach. The first one requires two extra types, and the second one removes the names from the call site, making ::new()
less clear when used with literals, e.g. ::new(5, "foo")
.
Are there good examples / a convention for something like this? Do I need to design my APIs differently (e.g. only use two separate types instead of one unified type)?