Returning an iterator and reverse iterator with match statement

I’m making a rubiks cube solver in rust. I’m trying to return a reverse iterator in the match statement, but I get this error:

expected struct std::ops::Range, found struct std::iter::Rev

I would expect to use something like (7…0) for the reverse, but that doesn’t work either.

Excuse my newbieness with the language, I’m quite new.

Thanks in advance! :slight_smile:

for i in match direction{
    RotationDirection::Clockwise => (1..8)
    RotationDirection::Counterclockwise => (1..8).rev(),
}{
    let swap_index = Cube::SIDE_ROTATION_SEQUENCE[i];
    Cube::swap_stickers(&mut self.sides, (side_name, 0, 0), (side_name, swap_index.0, swap_index.1));
}

The match has to return the same type from all arms, but you’re returning Range and Rev<Range>.

One way you can get around this is to wrap it in an enum – Either is really handy for this as it also implements Iterator when both of its types do. So you would wrap one arm in Left, the other in Right, and your iterator type will be Either<Range, Rev<Range>>.

1 Like

Ok, thanks. I’ll take a look into Either…

It works! :smiley:

for i in match direction{
    RotationDirection::Clockwise => Either::Left(1..8),
    RotationDirection::Counterclockwise => Either::Right((1..8).rev()),
}{
    let swap_index = Cube::SIDE_ROTATION_SEQUENCE[i];
    Cube::swap_stickers(&mut self.sides, (side_name, 0, 0), (side_name, swap_index.0, swap_index.1));
}

Also I realized my logic for rotating a rubik’s cube face was wrong

Rust will keep your code safe, but correctness is up to you. :wink:

2 Likes

I could just loop over my for loop twice :grin:

Although that would make it a little slower