仅在满足类型约束的情况下有条件地实现Rust特质

仅在满足类型约束的情况下有条件地实现Rust特质

本文介绍了仅在满足类型约束的情况下有条件地实现Rust特质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下结构:

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

如果T实现Default,我希望Foo::default()可用,否则 不可用.

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

是否可以在Rust中指定条件实现",并且仅当满足某些通用类型特征约束时才在其中实现特征?如果不满足约束条件,则不会实现目标特征(在这种情况下为Default),并且不会出现编译器错误.

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

推荐答案

@Kornel的答案指出,事实证明编译器已经有条件地实现了通用结构的特征.

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

仅当T满足定义Default的实现时指定的类型约束时,才为struct Foo<T>实现Default特质.在这种情况下,约束定义为where T: Default.因此,Foo<T>仅在T实现Default时实现Default.

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.

如上面的fn main()示例所示,当T不实现Default时,任何尝试使用Foo<T>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.

这篇关于仅在满足类型约束的情况下有条件地实现Rust特质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:29