I'm new to Rust, and have the following code which doesn't compile:
fn cells(&self) -> impl Iterator<Item = &Vector2<isize>> {
match self {
Kind::O => [(0, 0), (0, 1), (1, 0), (1, 1)],
Kind::I => [(-1, 0), (0, 0), (1, 0), (2, 0)],
Kind::T => [(-1, 0), (0, 0), (1, 0), (0, 1)],
Kind::L => [(-1, 0), (0, 0), (1, 0), (1, 1)],
Kind::J => [(-1, 1), (-1, 0), (0, 0), (1, 0)],
Kind::S => [(-1, 0), (0, 0), (0, 1), (1, 1)],
Kind::Z => [(-1, 1), (0, 1), (0, 0), (1, 0)],
}
.iter()
.map(From::from)
}
the compiler complains:
cannot return value referencing temporary value
I kind of understand that it's because the array will be dropped when the function returns.
but I cannot understand why the code compiles when we change it to the following:
fn cells(&self) -> impl Iterator<Item = &Vector2<isize>> {
match self {
Kind::O => &[(0, 0), (0, 1), (1, 0), (1, 1)],
Kind::I => &[(-1, 0), (0, 0), (1, 0), (2, 0)],
Kind::T => &[(-1, 0), (0, 0), (1, 0), (0, 1)],
Kind::L => &[(-1, 0), (0, 0), (1, 0), (1, 1)],
Kind::J => &[(-1, 1), (-1, 0), (0, 0), (1, 0)],
Kind::S => &[(-1, 0), (0, 0), (0, 1), (1, 1)],
Kind::Z => &[(-1, 1), (0, 1), (0, 0), (1, 0)],
}
.iter()
.map(From::from)
}
which only changes the array to a slice.