Goal:
To pass an EnumMap from the enum_map crate to a function
My error:
25 | fn print_board(board: &[CellStatus], celldict: & EnumMap<&CellStatus, &str>){
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait EnumArray<&str>
is not implemented for &CellStatus
Relevant code:
use enum_map::{enum_map, EnumMap};
enum CellStatus{
Empty,
Cross,
Circle,
}
fn print_board(board: &[CellStatus], celldict: & EnumMap<&CellStatus, &str>){
for cell in board {
println!("{}", celldict[cell]);
}
}
fn main() {
let cell_repr = enum_map! {
CellStatus::Empty => " _ ".to_string(),
CellStatus::Cross => " X ".to_string(),
CellStatus::Circle => " O ".to_string(),
};
}
Background:
Im trying to make a simple tic-tac-toe game as my first rust script. I havent implemented the logic yet of the game. I could make it work by just passing integers and a bunch of if statements but i wanted to write it in a more clean way.
Im guessing I have to implement something for my enum? but im not sure how to go about doing that.
Full code: https://pastebin.com/pZwqyvR2
Crate in question: https://docs.rs/enum-map/latest/enum_map/#
According to the documentation you posted, you have to derive
the crate's trait in order to use enum_map!
on that enum
. The only modification is just before your enum
definition:
#[derive(Enum)]
enum CellStatus {
Empty,
Cross,
Circle,
}
Also, the result of enum_map!
is a EnumMap<CellStatus, String>
in your case, not a EnumMap<&CellStatus, &str>
, Changing into that type should help. It complains that &CellStatus
does not implement a certain trait because that trait is automatically implemented by the derive macro for CellStatus
, and not for &CellStatus
. However, if you do this it will still not compile, because EnumMap
does not implement Index<&CellStatus>
, but only Index<CellStatus>
(which is a bit stupid if you ask me). Anyways, the best way to patch this IMO is to make CellStatus
Copy
. The following compiles:
use enum_map::{enum_map, Enum, EnumMap};
#[derive(Enum, Clone, Copy)]
enum CellStatus {
Empty,
Cross,
Circle,
}
fn print_board(board: &[CellStatus], celldict: &EnumMap<CellStatus, String>){
for cell in board {
println!("{}", celldict[*cell]);
}
}
fn main() {
let cell_repr = enum_map! {
CellStatus::Empty => String::from("_"),
CellStatus::Cross => String::from("X"),
CellStatus::Circle => String::from("O"),
};
}