Trait implementation priority


In current rust, code like

trait Hello {} impl Hello for int{} impl<T> Hello for T{}

would not accept by the compiler,because of the conflict implementation.

Will rustc support the feature like "if Hello trait is implememted for int ,use the implemented implementation. If it is not implemented ,use the default ‘Hello for T’ implementation" So it just means that “impl Hello for int” takes priority of “impl Hello for T”.

1 Like

Negative trait(?) bounds permit this, to some extent.

For your example you could do impl<T> Hello for T where T != int {}

I don’t think there’s any full specification of how it will all work though. Just a beautiful diamond in niko’s head.

1 Like

I write impl <T> Hello for T where T != int {}, but compiler complaints "error: expected :, found !="


Yes, this isn’t actually implemented yet :frowning:

1 Like

:frowning: Pitiful. Waiting for a fully functional language whole year


BTW: C++ resolves this via partial ordering (in overload resolution as well as selecting the right class template specialization). The more special template specialization wins. Example: Vec<int> is more special than Vec<T> for some type parameter T which is more special than U for some type parameter U.

What I like about this is that the C++ compiler “simply does the right thing” without me having to come up with constraints that are satisfied for exactly one impl (using negative predicates, for example). And I can later add a specialization without having to further restrict already existing specializations.

This would, for example, allow optimizing ToString for string slices simply by adding an impl of ToString for &'a str which is “more special” than an impl for T where T: Show.

But I guess these kinds of “overload resolution” rules can get pretty complicated. There are “patterns” like Vec<T> vs U and also different kinds of bounds involved where trait inheritance also induces a partial ordering. The book “C++ templates – The Complete Guide” dedicated a complete chapter for these kinds of overload resolution rules if I recall correctly and C++ doesn’t even have something like traits yet. :smile:


I would like to support specialization and prioritization eventually, but this will be a future feature.


Last year I tried to read the C++ spec on template argument deduction in order to implement some semi-complex SFINAE thing. Then I (figuratively) ran away screaming. It goes on for 18 pages, and that’s without involving function overload resolution…

If Rust is to have overlapping instances, priority needs to be much more explicit.


postpone to after 1.0?


This feature could be useful for this issue I think. In general, writing a generic impl and then writing more optimized implementations for specific types is a common pattern, hopefully this is supported soon.

closed #11

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.