Skip to content

Instantly share code, notes, and snippets.

@monadplus
Created November 2, 2022 13:02
Show Gist options
  • Save monadplus/5ac358dc7fac2861b678eab4cee6c6a1 to your computer and use it in GitHub Desktop.
Save monadplus/5ac358dc7fac2861b678eab4cee6c6a1 to your computer and use it in GitHub Desktop.
Rust: exploring GATs
use std::error::Error;
struct WindowsMut<'t, T> {
slice: &'t mut [T],
start: usize,
window_size: usize,
}
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
impl<'t, T> LendingIterator for WindowsMut<'t, T> {
type Item<'a> = &'a mut [T] where Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {
let retval = self.slice[self.start..].get_mut(..self.window_size)?;
self.start += 1;
Some(retval)
}
}
fn main() -> Result<(), Box<dyn Error>> {
let mut xs: [u8; 3] = [1, 2, 3];
println!("xs = {xs:?}");
let mut wm = WindowsMut {
slice: &mut xs,
start: 0,
window_size: 2,
};
// while let Some(slice) = wm.next() {
// slice.iter_mut().for_each(|x| {
// *x += 1;
// });
// }
let slice1 = wm.next().unwrap();
let slice2 = wm.next().unwrap(); // BOGUS
slice1.iter_mut().for_each(|x| {
slice2.into_iter().for_each(|y| {
*y += *x;
})
});
println!("xs = {xs:?}");
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment