kasra
kasra

Reputation: 372

Pass arrays of different length to generic function in Rust

I'm trying to pass an array of arrays to a generic function in Rust, however I'm having trouble doing so.

Here's my code:

pub const T: [[u8; 3]; 2] = [[0, 1, 0], [1, 1, 1]];
pub const L: [[u8; 3]; 2] = [[0, 0, 1], [1, 1, 1]];
pub const S: [[u8; 2]; 2] = [[1, 1], [1, 1]];

pub fn insert_shape<T: Iterator>(&mut self, shape: T)
    {
        for (i, item) in shape.iter().enumerate()
        {
            for (j, element) in item.iter().enumerate()
            {
                self.board.set_element(i, j, element);
            }
        }
    }


This give me an error that says type T doesn't have a method called iter. How can I fix this?

Upvotes: 0

Views: 558

Answers (1)

cafce25
cafce25

Reputation: 27566

Probably best to just take the arrays:

pub fn insert_shape<const W: usize, const H: usize, T>(&mut self, shape: [[T;W];H]) {
    for (i, item) in shape.iter().enumerate() {
        for (j, element) in item.iter().enumerate() {
            self.board.set_element(i, j, element);
        }
    }
}

If you really wanted you could also constrain the items of the iterator to be IntoIterator themselves.

pub fn insert_shape<I>(&mut self, shape: I)
where
    I: IntoIterator,
    I::Item: IntoIterator,
{
    for (i, item) in shape.into_iter().enumerate() {
        for (j, element) in item.into_iter().enumerate() {
            self.board.set_element(i, j, element);
        }
    }
}

Upvotes: 1

Related Questions