Is there a more idiomatic and speedy solution for enum usage?

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Location {
    Bottom,
    Left,
    Right,
    Top,
}

impl Location {
    pub fn iter() -> impl Iterator<Item = Self> {
        [Self::Bottom, Self::Left, Self::Right, Self::Top]
            .iter()
            .copied()
    }

    pub fn invert(self) -> Self {
        match self {
            Self::Bottom => Self::Top,
            Self::Left => Self::Right,
            Self::Right => Self::Left,
            Self::Top => Self::Bottom,
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::Location;

    #[test]
    fn test_location() {
        assert_eq!(Location::Bottom, Location::iter().next().unwrap());
        assert_eq!(None, Location::iter().skip(4).next());
        assert_eq!(Location::Right, Location::invert(Location::Left));
        assert_ne!(Location::Right, Location::invert(Location::Right));
    }
}

(Playground)

Output:


running 1 test
test tests::test_location ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s


running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


Errors:

   Compiling playground v0.0.1 (/playground)
    Finished test [unoptimized + debuginfo] target(s) in 2.94s
     Running unittests (target/debug/deps/playground-bdfd4e5dde87bcd9)
   Doc-tests playground

Your code seems alright. You’re talking about “more speedy”, in general if you’re testing performance in Rust, it’s necessary to turn on optimizations. The output

Finished test [unoptimized + debuginfo] target(s) in 2.94s

indicates unoptimized compilation, also if you’re worrying about the time displayed there (2.94 s), that’s how long compiling the code took, not how long running the tests took.

Thanks. With "speedy" I thought of if there is any API which would provide faster code in theory. Just to dive "deeper" and learn Rust better :wink:

As far as "idiomatic" goes, having iter be an associated function (no self argument) on Location that iterates over all values of Location is unconventional. Normally iter is a method on a collection that iterates over the values contained in the collection. In your case I'd suggest naming the function something else, like everything.