如何在各种类型的IntoIterator项上允许特征的多种实现?

编程入门 行业动态 更新时间:2024-10-28 18:29:27
本文介绍了如何在各种类型的IntoIterator项上允许特征的多种实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

只有在特征的不同实现之间因关联类型不同而不同时,Rust似乎无法区分它们.

Rust doesn't seem to distinguish between different implementations of a trait only if they differ by an associated type.

如何在所有类型的集合/迭代器上实现一种方法,但是对于它们所包含的每种具体类型都有特定的实现?

How can I implement a method on all kinds of collections/iterators, but have specific implementations for each concrete type they contain?

错误:特征 Foo [E0119]

代码:

trait Foo { fn foo(self); } impl<T> Foo for T where T: IntoIterator<Item=u32> { fn foo(self) { self.into_iter(); } } impl<T> Foo for T where T: IntoIterator<Item=u16> { fn foo(self) { self.into_iter(); } } fn main() { vec![0u32].foo(); vec![0u16].foo(); }

推荐答案

您不能直接执行通用表单,即问题#20400 .您必须引入一个可以用作 T :: Item 的绑定的特征,或者合并包装器类型.例如.第一个可能看起来像:

You can not do the generic form directly, which is issue #20400. You'll have to introduce either a trait that can be used as a bound on T::Item to merge the two implementations, or wrapper types. E.g. the first one might look like:

trait FooIterItem { // behaviours needed for Foo impl } impl FooIterItem for u32 { ... } impl FooIterItem for u16 { ... } impl<T> Foo for T where T: IntoIterator, T::Item: FooIterItem { ... }

更多推荐

如何在各种类型的IntoIterator项上允许特征的多种实现?

本文发布于:2023-11-03 19:48:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555927.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:特征   多种   类型   如何在   IntoIterator

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!