Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: How to implement Index with interim view that owns an object
I have this code:
pub trait Index<'a, Idx>
where
Self: 'a,
Idx: ?Sized,
{
type Output: ?Sized + 'a;
fn index(self, index: Idx) -> Self::Output;
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
struct Image(u32);
impl<'a> Index<'a, u8> for Image {
type Output = Row<Self>;
fn index(self, index: u8) -> Self::Output {
Row { column: index * 9, inner: self }
}
}
struct Row<T> {
column: u8,
inner: T
}
impl<'a> Index<'a, u8> for Row<Image> {
type Output = u8;
fn index(self, index: u8) -> Self::Output {
1 & (self.inner.0 >> self.column + index) as u8
}
}
fn main() {
let img = Image(u32::MAX / 5);
let element = img.index(0).index(0);
// let element = img[0][0] // How?
dbg!(element);
}
How can I rewrite this so that I can have the commented out line, by using the Index
trait from the standard library? Is it even possible?
9 posts - 4 participants
🏷️ rust_feed