[英]Why is Rust ok with accepting a different struct when implementing the same trait?
[英]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())
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.