简体   繁体   English

从特质和专业化实施

[英]Implementing from trait and specialization

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.按照专业化RFC ,我应该可以有多种impl相同的第traitstruct指定一个默认。

I have the code:我有代码:

#![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.这是一个与第一个冲突的替代实现。

Specialization requires that all types matching your second impl also match your first impl .专业化要求与您的第二个impl匹配的所有类型也与您的第一个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:

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.该 RFC 提出了一种专门化设计,它允许多个 impl 块应用于相同的类型/特征,只要其中一个块明显比另一个“更具体”。

Changing your trait definition to将您的特征定义更改为

trait Dummy: Into<u32> {}

makes your code compile.使您的代码编译。

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

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

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