Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing from trait and specialization

Tags:

rust

traits

According to the specialization RFC, I should be able to have multiple impls of the same trait on a struct by specifying one as default.

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.

like image 612
StevenDoesStuffs Avatar asked May 26 '19 01:05

StevenDoesStuffs


1 Answers

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. In other words the bounds of your specialization need to be a strict subset of the bounds of the default implementation. From the 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.

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.

like image 189
Richard Avatar answered Oct 18 '22 17:10

Richard