问题描述
根据专业化RFC,我应该能够在一个 struct
上有多个相同 trait
的 impl
,通过指定一个作为默认值.
According to the specialization RFC, I should be able to have multiple impl
s of the same trait
on a struct
by specifying one as default.
我有代码:
#![feature(specialization)]
struct A(u32);
trait Dummy {}
impl<T> From<T> for A
where
T: Into<u32>,
{
default fn from(item: T) -> Self {
A(item.into())
}
}
impl<T> From<T> for A
where
T: Dummy,
{
fn from(item: T) -> Self {
A(2)
}
}
即使其中一个实现是默认的,编译器仍然告诉我这两个实现是冲突的.
Even though one of the implementations is default, the compiler still tells me that the two are conflicting implementations.
推荐答案
您的第二个实现不是第一个的专业化.这是一个与第一个冲突的替代实现.
Your second implementation is not a specialization of the first. It's an alternative implementation that conflicts with the first.
专业化要求与您的第二个 impl
匹配的所有类型也与您的第一个 impl
匹配.换句话说,您的专业化边界需要是默认实现边界的严格子集.来自 RFC:
Specialization requires that all types matching your second impl
also match your first impl
. In other words the bounds of your specialization need to be a strict subset of the bounds of the default implementation. From the RFC:
该 RFC 提出了一种专门化设计,它允许多个 impl 块应用于同一类型/特征,只要其中一个块明显比另一个更具体".
将您的特征定义更改为
trait Dummy: Into<u32> {}
使您的代码编译.
查看 https://github.com/rust-lang/rfcs/blob/master/text/1210-impl-specialization.md 了解更多详情.
Check out https://github.com/rust-lang/rfcs/blob/master/text/1210-impl-specialization.md for more details.
这篇关于从特质和专业化实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!