Custom Index to static array

Hi!!!
I want indexing the following type:

#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Matrix2x2<T>([[T; 2]; 2]);

impl<T> Matrix2x2<T> {
    pub fn new(data_input: [[T; 2]; 2]) -> Matrix2x2<T> {
        Matrix2x2(data_input)
    }
}

with a tuple (usize, usize) and i have implementing the Index trait like so:

impl<T> Index<(usize, usize)> for Matrix2x2<T> {
    type Output = T;
    fn index(&self, index: (usize, usize)) -> &T {
        self[index.0][index.1]
    }
}

but i have errors, what i missing??? Thanks in advance!!!

Your index function actually calls itself which is obviously not what you want. One way around this would be to implement index on Matrix2x2 directly and then call that from the Index trait.

A quick example:

impl<T> Matrix2x2<T> {
    pub fn new(data_input: [[T; 2]; 2]) -> Matrix2x2<T> {
        Matrix2x2(data_input)
    }
    // implement the index function here.
    pub fn index(&self, index: (usize, usize)) -> &T {
        &self.0[index.0][index.1]
    }
}
impl<T> Index<(usize, usize)> for Matrix2x2<T> {
    type Output = T;
    fn index(&self, index: (usize, usize)) -> &T {
        // explicitly call the Maxtrix2s2 index function.
        Matrix2x2::index(&self, index)
    }
}
1 Like

You need to return a reference, and you likely want to index the inner array

&self.0[index.0][index.1]
2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.