Avba
Avba

Reputation: 15296

How to implement Default for a generic struct?

I have a generic struct and want to provide a concrete default implementation which will also allow user to override a value of the default field, but am getting compile errors:

struct MyStruct<A, B, C> {
    pub a: A,
    pub b: B,
    pub c: C,
}

impl<A, B, C> MyStruct<A, B, C>
where
    A: Trait1,
    B: Trait2,
    C: Trait3,
{
    pub fn foo() {}
}

trait Trait1 {}
trait Trait2 {}
trait Trait3 {}

I can create instances of MyStruct explicitly:

struct SomeA();
impl Trait1 for SomeA {}
struct SomeB();
impl Trait2 for SomeB {}
struct SomeC();
impl Trait3 for SomeC {}

let a = SomeA();
let b = SomeB();
let c = SomeC();

let my_struct = MyStruct { a: a, b: b, c: c }; // compiles

Now I want to implement Default which will also allow overriding a particular field with a different value when necessary (allow partial default?). Not sure on the syntax:

impl Default for MyStruct<SomeA, SomeB, SomeC> {
    fn default() -> Self {
        ...
    }
}

Playground

Upvotes: 6

Views: 3424

Answers (1)

Daniel Wagner-Hall
Daniel Wagner-Hall

Reputation: 2606

You can achieve this by only implementing Default if A, B, and C all implement Default:

impl <A, B, C> Default for MyStruct<A, B, C> where A: Default, B: Default, C: Default {
    fn default() -> Self {
        Self {
            a: A::default(),
            b: B::default(),
            c: C::default(),
        }   
    }   
}

Upvotes: 6

Related Questions