繁体   English   中英

有没有办法在 Rust 中实现具有不同通用约束的相同结构的特征?

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

假设我有一个 struct S<T>并且我想用不同的泛型T约束来实现它来表征Default

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 中没有办法做到这一点。

您可以在夜间 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM