I'm teaching Rust, and so I go to adventofcode (parallel with boring reading rustbook).
And in one task I need to track direction, during moving and rotations such as "Straight / Left / Back / Right" && "Straight + Right + Right == Back".
*) suppose for a second, that "absolute direction" and "relative direction" are represented as single type.
So I trying to solve this issue using enums. And during this I need two things:
- Contiguosly place discriminants from "integer 0" to last
- Get discriminants count (or "enum size") either straightforward or using some tricks.
But I can't do the second thing.
enum Dir {
Up,
Left,
Down,
Right,
//Last = (Dir::Right) as isize,
}
impl Dir {
fn add_dir(&self, add_dir: &Self) -> Self {
let last = Dir::from_int((self.to_int() + add_dir.to_int) / (Dir::Last.to_int() + 1));
return last;
}
}
So the questoin is: how can I implement domain-specific, i.e. type-safe, modulo arithmetic in rust (with no performance requirements if it's important).
======= Updated: The local and narrow question is - how to get constant "4" (modulo for modular arithmetic), but don't type it as literal (the last thing, typing constants as literal - is a very errorfull way when programmer starts to change his code).