Search code examples
rustgeneric-programming

Conditionally implement a Rust trait only if a type constraint is satisfied


I have the following struct:

pub struct Foo<T> {
    some_value: T,
}

impl<T> Foo<T> {
    pub fn new(value: T) -> Self {
        Self { some_value: value }
    }
}

// Implement `Default()`, assuming that the underlying stored type
// `T` also implements `Default`.
impl<T> Default for Foo<T>
where
    T: Default,
{
    fn default() -> Self {
        Self::new(T::default())
    }
}

I would like Foo::default() to be available if T implements Default, but not available otherwise.

Is it possible to specify "conditional implementation" in Rust, where we implement a trait if and only if some generic type trait constraint is satisfied? If the constraint is not satisfied, the target trait (Default in this case) is not implemented and there is no compiler error.

In other words, would is it possible to use the generic struct above in the following way?

fn main() {
    // Okay, because `u32` implements `Default`.
    let foo = Foo::<u32>::default();

    // This should produce a compiler error, because `Result` does not implement
    // the `Default` trait.
    //let bar = Foo::<Result<String, String>>::default();

    // This is okay. The `Foo<Result<...>>` specialisation does not implement
    // `Default`, but we're not attempting to use that trait here.
    let bar = Foo::<Result<u32, String>>::new(Ok(42));
}

Solution

  • As pointed out by @Kornel's answer, it turns out the compiler already conditionally implements traits of generic structs.

    The Default trait is only implemented for struct Foo<T> if T satisfies the type constraints specified when defining the implementation of Default. In this case, the constraints were defined as where T: Default. Therefore, Foo<T> only implements Default if T implements Default.

    As shown by the fn main() example above, any attempt to use the Foo<T>'s Default implementation when T does not implement Default produces a compiler error.