▲ 54 r/rust
I'm trying to program a simple chess engine and I wanted an easy way to convert an enum into a number and vice versa. For the first case it seemed simple enough, I could just do as usize, but for the second it seemed more complicated. This is the implementation I ended up with:
#[derive(Copy, Clone, Debug)]
pub enum Piece {
Pawns,
Knights,
Bishops,
Rooks,
Queens,
King,
}
impl TryFrom<usize> for Piece {
type Error = String;
fn try_from(value: usize) -> Result<Self, Self::Error> {
if value <= 5 {
Ok(unsafe { std::mem::transmute::<u8, Piece>(value as u8) })
} else {
Err("Invalid value for Piece".to_string())
}
}
}
It seems to work, but I was wondering if it's a good idea? Is it going to give me problems down the line?
u/JustJeffrey — 19 days ago