[英]Which trait bound should I use for a type that must implement the "iter" function
I am trying to implement a struct composed of a generic field which type must implement the non-consuming "iter" method (see below).我正在尝试实现一个由泛型字段组成的结构,该类型必须实现非消耗的“iter”方法(见下文)。
struct Node<T> {
key: T
}
impl<T> Node<T> where T: ?? {
fn do_stuff(&self) {
for e in self.key.iter() {
/* ... */
}
}
}
fn main() {
let n1 = Node { key: "foo".to_owned() };
n1.do_stuff();
let n2 = Node { key: vec![1, 2, 3] };
n2.do_stuff();
}
Which trait bound should I associate with the parameter T
?我应该将哪个特征边界与参数
T
相关联?
The trait bound you're looking for is &T: IntoIterator
.您正在寻找的 trait bound 是
&T: IntoIterator
。 As a convention, types that provide a non-consuming iter()
also provide an implementation of IntoIterator
for a reference to the type.作为惯例,提供非消费
iter()
还提供IntoIterator
实现以引用该类型。 (Likewise, iter_mut()
is equivalent to IntoIterator
for &mut T
.) (同样,
iter_mut()
等价于&mut T
IntoIterator
。)
For example:例如:
impl<T> Node<T>
where
for<'a> &'a T: IntoIterator,
{
fn do_stuff(&self) {
for e in &self.key { /* ... */ }
}
}
Note, however, that this won't compile with key: "foo".to_owned()
simply because a String
is not iterable.但是请注意,这不会使用
key: "foo".to_owned()
编译,因为String
不可迭代。
Which trait bound should I associate with the parameter
T
?我应该将哪个特征边界与参数
T
相关联?
There is no such a trait in the standard library, the iter()
is an inherent method – it doesn't come from a trait implementation.标准库中没有这样的特征,
iter()
是一个固有的方法——它不是来自特征实现。 You could, of course, create your own trait (eg, Iter
) that specifies iter()
.当然,您可以创建自己的特征(例如,
Iter
)来指定iter()
。
If you are working with a generic type and need to ensure that such type's values can be turned into an iterator, you may want to consider bounding the type to the IntoIterator
trait.如果您正在使用泛型类型并需要确保此类类型的值可以转换为迭代器,您可能需要考虑将类型
IntoIterator
到IntoIterator
特征。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.