简体   繁体   中英

How can I implement trait B for all types that implement trait A if both traits are implemented for references?

We have two traits A and B for which

  1. I can trivially implement B for all types that implement A .
  2. I can trivially implement A for references to any type implementing A .
  3. I can trivially implement B for references to any type implementing B .

Actually doing all three leads to a conflict, because now references to types that implement A would have two implementations of B for them. One due to the impl<T: A> A for &T and one transitively due to the impl<T: A> B for T (and then the impl<T: B> B for &T .

I can't remove the impl<T: B> B for &T , because there might be types that implement B but not A

Here's an example code exhibiting the behaviour.

trait A {}
trait B {}

impl<'a, T: A> A for &'a T {}
impl<T: A> B for T {}

impl<'a, T: B> B for &'a T {}

which results in the following error:

error[E0119]: conflicting implementations of trait `B` for type `&_`:
  |
  | impl<T: A> B for T {}
  | --------------------- first implementation here
  | impl<'a, T: B> B for &'a T {}
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `&_`

Is it possible to use the Rust typesystem in a way to ensure that when there is an impl B for &A , we don't create one for &B ?

There has been some discussion on the Rust internals forum on this topic, starting with a blog post by Nicholas Matsakis about how to handle the issue of overlapping trait implementations.

Today, (unstable) Rust has some impl specialisation , but that only works for strictly more specific impls of a more generic one.

So I think the answer is that there isn't a good way to do it today, but at some point in the future there's a good chance that Rust will evolve to allow expressing overlapping trait impls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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