Is there an ergonomic way of initializing a struct in this situation?

I have a couple structs in my code that look like this:

struct MyStruct {
    // This type doesn't have a default value
    non_default_value: NonDefaultValue,
    // around 10 fields that do have a default value
    f1: f32,
    f2: f32,
    ...
}

It isn't possible to create an instance of this struct like this because ..Default::default() syntax only works inside structs which implement Default which this struct cannot do since it has a field with non default value:

// Doesn't work
MyStruct {
    non_default_value,
    ..Default::default()
}

Is there a concise way of telling the compiler that I want the rest of the fields to have their default values. In C/C++ I can just leave the fields uninitialized. I have encountered this issue one too many times recently and the boilerplate has become frustrating.

There is an RFC for this feature, but I don't believe it's been implemented yet. For details, see:

Also, I don't know if the partial_default crate is useful, but it may be worth a look.

If you don't want the literal FRU syntax, you can just write a constructor method and use it instead of literals.

Or, you can pull out the fields with a default value into another struct.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.