Alberto
Alberto

Reputation: 15

Mismatched types error when implementing a generic struct with a specific type parameter

I'm trying to implement a generic struct A1Implementation that takes a type parameter B which should implement the trait A1. However, when I try to create an instance of A1Implementation with a specific type Ex1_A1, the compiler gives me the following error:

mismatched types
expected type parameter `B`
       found struct `Ex1_A1`

Here's my code snippet:

struct A1Implementation<B: A1>(B);

impl <B: A1> Default for A1Implementation<B> {
    fn default() -> Self {
        Self(Ex1_A1)
    }
}

I understand that the error is indicating that the expected type parameter B is not the same as the found type Ex1_A1. However, Ex1_A1 does indeed implement the A1 trait.

Could someone help me understand why this error is occurring and how I can achieve a similar behavior? I want to create an instance of A1Implementation with a specific type that implements the A1 trait.

Upvotes: 0

Views: 60

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71350

Self always means "the type in the impl clause".

The type in the impl clause is A1Implementation<B>, which is not the same as A1Implementation<Ex1_A1> that you return.

You have two options:

  1. Implement Default for any A1Implementation, and return the default value for B:

    impl<B: A1 + Default> Default for A1Implementation<B> {
        fn default() -> Self {
            Self(B::default())
        }
    }
    

    (This impl can be derived).

    This allows any type parameter to be used with the Default impl, but does not provide a default type for it.

  2. Impl Default only for A1Implementation<Ex1_A1>:

    impl Default for A1Implementation<Ex1_A1> {
        fn default() -> Self {
            Self(Ex1_A1)
        }
    }
    

    This chooses the opposite trade-off: allow only Ex1_A1, but also default to it.

Upvotes: 2

Related Questions