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

岁酱吖の 提交于 2020-01-05 05:55:05

问题


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));
}

回答1:


For this specific instance, the implementation provided by derive(Default) does exactly what you've asked for:

#[derive(Default)]
pub struct Foo<T> {
    some_value: T,
}

See also:

  • Deriving a trait results in unexpected compiler error, but the manual implementation works



回答2:


Your example, after fixing minor syntax issues, does work:

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())
    }
}

fn main() {}

Playground




回答3:


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.



来源:https://stackoverflow.com/questions/48037963/conditionally-implement-a-rust-trait-only-if-a-type-constraint-is-satisfied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!