Iterating over a Vec<Vec<T>> struct

Viewed 105

With the below code snippet, Rustc gives the error cannot index into a value of type Matrix<T>.

What would be the proper way to access the vectors inside the Matrix struct in such cases?

pub struct Matrix<T>(pub Vec<Vec<T>>);

impl<T> Add for Matrix<T> {

    fn add(self, other_matrix: Self) -> Option<Self> {

        let mut vector_1 = vec![];

        for x in 0..self.len() {
            for y in 0..self[x].len() {
                let total = self[x][y] + other_matrix[x][y];
                vector_1.push(total);
            }
            // ... //
        }
    }

}

Any advice would be much appreciated!

1 Answers

You use identifier.order syntax to access a member of a tuple struct. In your case, it becomes self.0, and your snippet becomes like this:

for x in 0..self.0.len() {
  for y in 0..self.0[x].len() {
    let total = self.0[x][y] + other_matrix.0[x][y];
    vector_1.push(total);
  }
...
Related