Only setting one field in a Rust `Default` implementation

Viewed 345

I have a Rust struct with a large number of fields, all of which are themselves Default. I'd like to create a custom impl Default for it, with the following semantics:

  1. One of the fields has a custom value
  2. All other fields get their value from their Default::default

Here's how I hoped to do that:

impl Default for Foo {
    fn default() -> Self {
        Self {
            thing: 2,
            ..Default::default()
        }
    }
}

...but that actually causes unchecked recursion, since ..Default::default() calls Self::default() rather than $member::default() for each member of Self.

Is there any way to accomplish this, short of writing a custom macro or explicitly listing every field?

1 Answers

You can use the derivative crate to achieve this. It provides alternative versions of some of the standard library derive macros with additional customizability:

#[derive(Debug, Derivative)]
#[derivative(Default)]
struct Foo {
    foo: u8,
    #[derivative(Default(value="2"))]
    thing: u8,
}

Just using the standard library, you can either derive Default to get the default values for all fields, or implement it completely manually.

Related