rust - trait with functions that return an iterator -
i'm trying build trait functions return iterator.
my simple example looks this:
pub trait traita { fn things(&self) -> iterator<item=&u8>; } fn foo<a: traita>(a: &a) { x in a.things() { } } which not work because iterator size type not known @ compile time.
rust's libstd has 1 implementation of this, trait intoiterator.
/// conversion `iterator` pub trait intoiterator { /// type of elements being iterated type item; /// container iterating on elements of type `item` type intoiter: iterator<item=self::item>; /// consumes `self` , returns iterator on fn into_iter(self) -> self::intoiter; } the trait has peculiar by-value (self) formulation able express both “into iterator” , “borrow iterator” semantics.
demonstrated hashmap's intoiterator implementations. (they use hashmap's iterator structs iter , intoiter.) what's interesting here trait implemented type &hashmap<k, v, s> express “borrow iterator”.
impl<'a, k, v, s> intoiterator &'a hashmap<k, v, s> k: eq + hash, s: hashstate { type item = (&'a k, &'a v); type intoiter = iter<'a, k, v>; fn into_iter(self) -> iter<'a, k, v> { self.iter() } } impl<k, v, s> intoiterator hashmap<k, v, s> k: eq + hash, s: hashstate { type item = (k, v); type intoiter = intoiter<k, v>; /// creates consuming iterator, is, 1 moves each key-value /// pair out of map in arbitrary order. map cannot used after /// calling this. fn into_iter(self) -> intoiter<k, v> { /* ... */ } }
Comments
Post a Comment