Skip to content

Instantly share code, notes, and snippets.

@rrohrer
Created July 19, 2020 22:37
Show Gist options
  • Save rrohrer/aebadd9b3f2bb89b48b209ccbb978996 to your computer and use it in GitHub Desktop.
Save rrohrer/aebadd9b3f2bb89b48b209ccbb978996 to your computer and use it in GitHub Desktop.
Streaming Iterators in a Trait
trait HasIter<'a, T> {
type IterType: Iterator<Item = T>;
}
trait Collection<T>: for<'a> HasIter<'a, &'a T> {
fn iter<'a>(&'a self) -> <Self as HasIter<'a, &'a T>>::IterType;
}
struct Bar<T>(T);
struct BarIter<'a, T>(&'a Bar<T>);
impl<'a, T> Iterator for BarIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
Some(&(self.0).0)
}
}
impl<'a, T> HasIter<'a, &'a T> for Bar<T> {
type IterType = BarIter<'a, T>;
}
impl<T> Collection<T> for Bar<T> {
fn iter<'a>(&'a self) -> BarIter<'a, T> {
BarIter(self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment