Reputation: 25637
First "type" is an enum
pub enum Symbol {
X,
O,
}
Second is a also an enum
pub enum CellContent {
Move(Symbol),
None,
}
Having these 3 only variants allowed
let cellX = CellContent::Move(Symbol::X);
let cellO = CellContent::Move(Symbol::O);
let cellEmpty = CellContent::None;
How can I compare a CellContent with a Symbol ?
assert_eq(cellX, Symbol::X);
assert_eq(cellY, Symbol::X);
I tried
impl PartialEq<Symbol> for CellContent {
fn eq(&self, other: &Symbol) -> bool {
if self == CellContent::None {
return false;
}
true;
}
}
the first comparison doesn't compile because can't compare &structs::CellContent
with structs::CellContent
and obviously i cannot return true in the other case but I must compare if self is a Move(Symbol::X) and other is a Symbol::X, or CellConent is a Move(Symbol::) and other is a Symbol::X
I have no idea of how to write these 3 comparison
Upvotes: 1
Views: 280
Reputation: 2561
You should derive Eq
and PartialEq
for your enums first, so that they can be compared to themselves. After that, you can check if a move is equal to a symbol, or always return false if there is no move:
#[derive(Debug, PartialEq, Eq)]
pub enum Symbol {
X,
O,
}
#[derive(Debug, PartialEq, Eq)]
pub enum CellContent {
Move(Symbol),
None,
}
impl PartialEq<Symbol> for CellContent {
fn eq(&self, other: &Symbol) -> bool {
match self {
CellContent::Move(symbol) => symbol == other,
CellContent::None => false,
}
}
}
fn main() {
let cellX = CellContent::Move(Symbol::X);
let cellO = CellContent::Move(Symbol::O);
let cellEmpty = CellContent::None;
assert_eq!(cellX, CellContent::None);
}
(I also derived Debug
to see prettier error messages)
Upvotes: 1