rust - 复杂泛型代码"conflicting implementations"错误,如何解决?

标签 rust

我有Base特质,实现 Foo<B>对于所有实现了 Bar<B> 的类型,现在我要特殊的工具Foo<B>对于所有 Foobar<B>结构,其中 B: Base :

trait Base {}


trait Foo<B: Base> {}


trait Bar<B: Base> {}


struct Foobar<B: Base> { _b: B }


// delete either, compile success
impl<B: Base, T: Bar<B>> Foo<B> for T {}
impl<B: Base> Foo<B> for Foobar<B> {}


fn main()
{
}

编译错误为:

<anon>:14:1: 14:41 error: conflicting implementations for trait `Foo` [E0119]
<anon>:14 impl<B: Base, T: Bar<B>> Foo<B> for T {}
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<anon>:14:1: 14:41 help: see the detailed explanation for E0119
<anon>:15:1: 15:38 note: note conflicting implementation here
<anon>:15 impl<B: Base> Foo<B> for Foobar<B> {}
          ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

这是 playground

最佳答案

您的 impl 是重叠的,对此没有一般性的解决方法(除了“如果您想稍后对其进行专门化,请避免一揽子 impl”)。

目前在 a RFC 中有可能拥有更专业的 impl 版本. this pull request 中尝试实现.

关于rust - 复杂泛型代码"conflicting implementations"错误,如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35127870/

相关文章:

rust - 什么时候应该使用函数指针而不是闭包?

generics - 如何表示返回的关联类型实现了特征?

rust - 为什么我们不应该在 HashSet::insert 中使用 & ?

json - 无法使用 Rustc-serialize 处理 JSON 中的可选字段

parsing - 将闭包作为参数并返回值,Fn或FnMut是否更惯用?

iterator - 在迭代另一个属性时修改结构的一个属性

iterator - 在拥有这些函数的结构上应用一些函数

rust - 如何从流中读取特定数量的字节?

gtk - GTK 中的 new_from_file()——我总是需要那个 "glade"文件吗?我可以嵌入它吗?

rust - 无法设置 Iron 框架响应的 header