I am trying to implement a struct composed of a generic field which type must implement the non-consuming "iter" method (see below).
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
?
CodePudding user response:
The trait bound you're looking for is &T: IntoIterator
. By convention, types that provide a non-consuming iter()
also provide an implementation of IntoIterator
for &T
. (Likewise, iter_mut()
comes in pair with an impl of IntoIterator
for &mut T
.)
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 accept key: "foo".to_owned()
simply because Rust strings are not iterable.
CodePudding user response:
Which trait bound should I associate with the parameter
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. You could, of course, create your own trait (e.g., Iter
) that specifies 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.