Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only setting one field in a Rust `Default` implementation [duplicate]

Tags:

rust

traits

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?

like image 880
yossarian Avatar asked Jun 26 '26 20:06

yossarian


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.

like image 177
Sven Marnach Avatar answered Jun 28 '26 12:06

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!