Priorities for trait implementations

There is a fundamental issue that any solution to this problem will meet, this is the infamous specialization unsoundness. The problem is that you can have lifetime bounds on traits. This means that you may have a single type that only partially implements a trait depending on its lifetime. As a result, a single type can have two implementations for a single trait. Suppose:

impl<'a> Bar for &'a str {
  fn bar(self) {}
}
impl Foo for &'static str {
  fn foo(self) {}
}
// now `&'static str` uses `Foo`
// but `&'a str` uses Bar

In this case &str has two different implementations for SomeTrait because of lifetime bounds. In my opinion, the only safe way to resolve this is to downcast the &'static str to a &'a str, since 'static: 'a. However, I don't know if more complex cases exist where this kind of resolution is impossible.

Concerning your proposal, it would be very counter intuitive if &str resolved to the Bar implementation, even though Foo had precedence. All in all, I prefer a more restrictive form of negative trait bounds to address this issue (although it also suffers from this same unsoundness).

2 Likes