简体   繁体   中英

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).

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 ?

The trait bound you're looking for is &T: IntoIterator . As a convention, types that provide a non-consuming iter() also provide an implementation of IntoIterator for a reference to the type. (Likewise, iter_mut() is equivalent to 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 compile with key: "foo".to_owned() simply because a String is not iterable.

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 (eg, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM