![](/img/trans.png)
[英]Conflicting trait implementations for types that clearly already implement the trait
[英]How to implement trait for types implementing another trait without conflicting implementations
我有一个广泛的基础特征。 有些类型只关心其功能的子集,所以我添加了一个子特征,要求用户实现更小的功能集。
此代码失败:
trait Base<T> {
fn foo(arg: bool);
}
// Ext is a narrowing of Base requiring user to provide alternative, simpler interface for the same functionality
trait Ext<T>: Base<T> {
fn bar();
}
// implement Base<T> for all types implementing Ext<T>
impl<T, E> Base<T> for E
where
E: Ext<T>,
{
fn foo(arg: bool) {
Self::bar();
}
}
struct Data<T>;
// error[E0119]: conflicting implementations of trait `Base<_>` for type `Data<_>`:
impl<T> Base<T> for Data<T> {
fn foo(arg: bool) {}
}
出现以下错误:
error[E0119]: conflicting implementations of trait `Base<_>` for type `Data<_>`:
--> src/lib.rs:22:1
|
11 | / impl<T, E> Base<T> for E
12 | | where
13 | | E: Ext<T>,
14 | | {
... |
17 | | }
18 | | }
| |_- first implementation here
...
22 | impl<T> Base<T> for Data<T> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `Data<_>`
|
= note: downstream crates may implement trait `Ext<_>` for type `Data<_>`
有趣的是,当我删除T
的一般性时,它会起作用:
trait Base {
fn foo(arg: bool);
}
// Ext is a narrowing of Base requiring user to provide alternative, simpler interface for the same functionality
trait Ext: Base {
fn bar();
}
// implement Base for all types implementing Ext
impl<E> Base for E
where
E: Ext,
{
fn foo(arg: bool) {
Self::bar();
}
}
struct Data;
// works just fine
impl Base for Data {
fn foo(arg: bool) {}
}
stackoverflow 上的其他一些帖子提到了类似的问题,但它们通常存在外来特征(来自标准库的特征)的问题。 就我而言,特征和类型都是本地的,因此据我所知,孤儿规则不应该生效。
基本上,错误提到downstream crates may implement trait 'Ext<_>' for type 'Data<_>'
,这是不正确的,因为Ext
和Data
对于这些板条箱来说都是外来的。
总而言之,我的问题是:
T
的版本不会被拒绝,即使它几乎是相同的一揽子 impl?您看到错误的原因是 impl Base for E 和 impl Base for Data之间可能存在冲突
这些都是 generics,所以理论上我可以创建自己的结构并实现特征Base<T>
以及特征Ext<T>
。 如果我这样做,您的代码将为Base<T>::foo
创建重复的实现,因为两个impl
块都在实现Base<T>
。
当您从代码中删除T
时,它会变得更加具体。 您将为E
实现Base
和为Data
实现Base
。 如果添加以下内容,您可以在自己的第二个代码示例中看到相同的错误
impl Ext for Data {
fn bar() {}
}
这是相同的基本信息。 唯一的区别是你的第一个例子只提供了碰撞的可能性,而第二个(加上我的补充)实际上导致了碰撞。
至于解决方法... Rust 特征并不是真正的 inheritance 所以我想说的生锈方法是为您想要的每个函数子集设置单独的特征,而不是尝试创建特征层次结构。
如果您的程序确实需要具有 inheritance 类型特征,则避免使用 generics 或将它们绑定到具体类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.