从特质和专业化实施

Implementing from trait and specialization

根据 specialization RFC,我应该能够在 struct 上有多个相同 traitimpl,方法是指定一个作为默认值。

我有代码:

#![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)
    }
}

即使其中一个实现是默认的,编译器仍然告诉我这两个实现是冲突的。

你的第二个实现不是第一个的专业化。这是与第一个冲突的替代实现。

专业化要求与您的第二个 impl 匹配的所有类型也与您的第一个 impl 匹配。换句话说,您的专业化边界必须是默认实现边界的严格子集。来自 RFC:

This RFC proposes a design for specialization, which permits multiple impl blocks to apply to the same type/trait, so long as one of the blocks is clearly "more specific" than the other.

将你的特征定义更改为

trait Dummy: Into<u32> {}

使您的代码编译。

查看 https://github.com/rust-lang/rfcs/blob/master/text/1210-impl-specialization.md 了解更多详情。