Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 17, 2019 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rust-play/d0355001e90db38d1bccce9af76e8ef6 to your computer and use it in GitHub Desktop.
Save rust-play/d0355001e90db38d1bccce9af76e8ef6 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
struct Flatten<I, S>
where
I: Iterator,
S: Iterator,
{
base: I,
inner: S,
}
impl<I> Flatten<I, <I::Item as IntoIterator>::IntoIter>
where
I: Iterator,
<I as Iterator>::Item: IntoIterator,
{
fn new (mut it: I) -> Flatten<I, <I::Item as IntoIterator>::IntoIter> {
let inner = it.next().unwrap().into_iter();
Flatten {
base: it,
inner,
}
}
}
impl<I> Iterator for Flatten<I, <I::Item as IntoIterator>::IntoIter>
where
I: Iterator,
<I as Iterator>::Item: IntoIterator,
{
type Item = <<I as Iterator>::Item as IntoIterator>::Item;
fn next(&mut self) -> Option<<I::Item as IntoIterator>::Item> {
loop {
match self.inner.next() {
Some(a) => return Some(a),
None => {},
}
match self.base.next() {
Some(a) => self.inner = a.into_iter(),
None => return None,
}
}
}
}
fn main() {
let mut hilly = vec![[1, 2, 3], [4, 5, 6]];
println!("{:?}", Flatten::new(hilly.iter()).collect::<Vec<_>>());
hilly.clear();
println!("{:?}", Flatten::new(hilly.iter()).collect::<Vec<_>>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment