[英]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 我们有两个特征
A
和B
B
for all types that implement A
. A
所有类型简单地实现B
A
for references to any type implementing A
. A
来引用任何实现A
类型。 B
for references to any type implementing B
. B
以引用任何实现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. 实际上,所有三个都会导致冲突,因为现在对实现
A
类型的引用将为它们提供两个B
实现。 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
. 一个是由于
impl<T: A> A for &T
而一个是由于impl<T: A> B for T
(然后是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
我无法删除
impl<T: B> B for &T
的impl<T: B> B for &T
,因为可能存在实现B
而不是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
? 是否有可能以某种方式使用Rust类型系统以确保当有
impl B for &A
的impl B for &A
,我们不为&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. 关于这个主题的Rust内部论坛已经有一些讨论 ,首先是Nicholas Matsakis关于如何处理重叠特征实现问题的博客文章 。
Today, (unstable) Rust has some impl specialisation , but that only works for strictly more specific impls of a more generic one. 今天,(不稳定)Rust有一些impl专门化 ,但这只适用于更通用的更严格的更具体的impl。
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. 所以我认为答案是今天没有一个好方法可以做到这一点,但是在将来的某个时候,Rust很有可能会发展为允许表达重叠的特质动作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.