TL;DR at the end
Hi there, I'm working on a simple solver for a tile based board game and I'm using an object storing cardinal directions to easily walk through the board. For example, I'm dropping a new tile on the board and I want to check what tile is on the left, conceptually I do new_tile.x + direction.west.x
(pseudo-code here).
First test with enum
My first approach on this was to declare an enum to hold all 4 cardinal directions:
enum Direction {
North,
East,
South,
West,
}
Then what I'd like to do is storing or associate x/y values with enum variants, e.g. North = { x: 0, y: 1 }
.
So I added this to the previous code:
impl Direction {
fn value(&self) -> (i8, i8) {
match *self {
Direction::North => (0, 1),
Direction::East => (1, 0),
Direction::South => (0, -1),
Direction::West => (-1, 0),
}
}
}
But in the end, I'm never directly calling for an enum variant, I'm always looping through all the directions through an array of values
impl Direction {
fn values() -> [(i8, i8); 4] {
[
Direction::North.value(),
Direction::East.value(),
Direction::South.value(),
Direction::West.value(),
]
}
}
Another approach with struct
Based on my need and what Rust offers, I was thinking about switching to a struct
with const
fields:
struct Direction {}
impl Direction {
const NORTH: (i8, i8) = (0, 1);
const EAST: (i8, i8) = (1, 0);
const SOUTH: (i8, i8) = (0, -1);
const WEST: (i8, i8) = (-1, 0);
fn values() -> [(i8, i8); 4] {
[
Direction::NORTH,
Direction::EAST,
Direction::SOUTH,
Direction::WEST,
]
}
}
Because I started to implement functions, it then seemed to me that it was more accurate to use a struct
.
What's the best? (TL;DR)
So technically, I can achieve my goal with 2 different writings but conceptually, which object would make more sense to you?
Bonus
While talking about clear way to write things, would it makes sense to convert plain (i8, i8)
to struct Vector(i8, i8)
or even struct Vector { x: i8, y: i8 }
?