有什么方法可以在 Rust 中实现具有相同结构的不同通用约束的特征吗?

Is there any way to implement a trait with the same struct of different generic constraints in Rust?

假设我有一个结构 S<T> 并且我想将它实现为特征 Default 具有不同的通用类型约束 T:

struct S<T> { ... }


impl<T> Default for S<T> 
where
    T: Ord
{
    fn default() -> Self {
        Self::new()
    }
}

impl<T> Default for S<T>
where
    T: Ord + Default
{
    fn default() -> Self {
        Self::build(T::default())
    }
}

然而,编译器抱怨:

error[E0119]: conflicting implementations of trait std::default::Default for type S<_>

有没有办法编译这样的代码?

在稳定的 Rust 中无法做到这一点。

您可以在 nightly Rust 上使用(不稳定且不可靠!)specialization 功能:

#![feature(specialization)]

struct S<T> {
    x: Option<T>
}

impl<T> S<T> {
    fn new() -> Self { Self { x: None } }
    fn build(x: T) -> Self { Self { x: Some(x) } }
}


impl<T> Default for S<T> 
where
    T: Ord
{
    default fn default() -> Self {
        Self::new()
    }
}

impl<T> Default for S<T>
where
    T: Ord + Default
{
    fn default() -> Self {
        Self::build(T::default())
    }
}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=ee24c383878f7a32c53d12211b69ab4f