Last active
August 7, 2021 15:04
-
-
Save Keating950/0a34ecdc9ab39af3a8c1bb5d6a8a839a to your computer and use it in GitHub Desktop.
Example of a Rust generator and a corresponding Iterator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(generators, generator_trait)] | |
use std::{ | |
iter, | |
ops::{Generator, GeneratorState}, | |
pin::Pin, | |
}; | |
pub struct Grid<const R: usize, const C: usize> { | |
grid: [[bool; C]; R], | |
} | |
impl<const R: usize, const C: usize> Grid<R, C> { | |
pub fn col<'a>(&'a self, idx: usize) -> impl Iterator<Item = bool> + 'a { | |
let mut i = 0; | |
let mut gen = move || { | |
while i < R { | |
yield self.grid[i][idx]; | |
i += 1; | |
} | |
return; | |
}; | |
iter::from_fn(move || match Pin::new(&mut gen).resume(()) { | |
GeneratorState::Yielded(val) => Some(val), | |
GeneratorState::Complete(_) => None, | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment