Default ergonomics
โ Rust ๐ 2025-08-11 ๐ค surdeus ๐๏ธ 10If one has a struct that contains a member that does not derive Default, but has many members that do, is there some way to default-initialize all of its Default members?
enum NameOrId {
Id(u64),
Name(String)
}
struct Foo {
noi: NameOrId, // There's no default,
thing1: Option<u64>,
// ..
thing99: Option<String>
}
Ideally:
Foo {
noi: NameOrId::Id(42),
..default()
}
We could obviously just split Foo up:
#[derive(Default)]
struct FooDefaultable {
thing1: Option<u64>,
// ..
thing99: Option<String>
}
struct Foo {
noi: NameOrId, // There's no default,
defaultable: FooDefaultable
}
I realized over past few days that we have quite a few big explicit struct initialization because only a single member doesnโt/canโt implement Default.
2 posts - 2 participants
๐ท๏ธ Rust_feed