Default ergonomics

โš“ Rust    ๐Ÿ“… 2025-08-11    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 4      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Default ergonomics

If 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

Read full topic

๐Ÿท๏ธ Rust_feed