生 rust 枚举工具+= 1

ss2ws0br  于 2023-01-26  发布在  其他
关注(0)|答案(2)|浏览(135)

我试着写扫雷我有枚举与状态的细胞,并试图写函数,以认识到有多少地雷周围。

enum CellStatus {
  CLOSED,  
  MINED,
  FLAGED,
  OPENED,
  ONE,
  TWO,
  THREE,
  FOUR,
  FIVE,
  SIX,
  SEVEN,
  EIGHT
}

if mine_area[i+1][j+1] == CellStatus::MINED {
        mine_area[i][j] += 1;
}

这是什么编译器建议我:

error[E0368]: binary assignment operation `+=` cannot be applied to type `CellStatus`
   --> src/main.rs:25:9
    |
25  |         mine_area[i][j] += 1;
    |         ---------------^^^^^
    |         |
    |         cannot use `+=` on type `CellStatus`
    |
note: an implementation of `AddAssign<_>` might be missing for `CellStatus`
   --> src/main.rs:126:1
    |
126 | enum CellStatus {
    | ^^^^^^^^^^^^^^^ must implement `AddAssign<_>`
note: the following trait must be implemented

在官方AddAssign上,它是Point的示例,并且它结构不是枚举。
BrownieInMotion建议我在Opened中使用u8,它确实很有帮助,但不是问题的解决方案。

ulmd4ohb

ulmd4ohb1#

使用这样的枚举又如何呢?

enum Status {
    Closed,
    Flagged,
    Mined,
    Opened(u8),
}

但是,我对如何持有地雷状态有点困惑,我认为在表示地雷应该如何显示时使用这个是有意义的,但我看到您也在使用这个枚举来持有董事会状态本身。

if mine_area[i+1][j+1] == CellStatus::MINED

我认为这个检查没有意义,因为这个枚举不适合表示董事会的状态;它更适合于表示棋盘应该如何绘制。
例如,可以标记或不标记具有mine的单元格,但是枚举一次只能表示这些特征中的一个。

dly7yett

dly7yett2#

下面是正确的操作方法:

impl AddAssign for Status {
  fn add_assign(&mut self, other: Self) {
    *self = match *self {
      Status::Opened(count) => match other {
        Status::Opened(count2) => Status::Opened(count + count2),
        _ => other,
      },
      _ => other
    }
  }
}

我的最终实现是:

use std::ops::AddAssign;

fn main() {
  let width:u16 = 5;
  let heigh:u16 = 5;

  let mut game_area = vec![vec![Status::Closed; width.into()]; heigh.into()];

  game_area[1][1] = Status::Opened(0);
  game_area[1][1] += Status::Opened(1);
  game_area[1][1] += Status::Opened(1);
  game_area[1][1] += Status::Opened(1);

  println!("{}", game_area[1][1].as_str());
}

#[derive(Clone)]
enum Status {
  Closed,
  Flagged,
  Mined,
  Opened(u8),
}

const MINE_CHAR: [&str; 9] = ["🔳", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣"];

impl Status {
  pub fn as_str(&self) -> String {
    match self {
      Status::Mined => "💣".to_string(),
      Status::Closed => "⬜".to_string(),
      Status::Flagged => "🚩".to_string(),
      Status::Opened(i) => MINE_CHAR[*i as usize].to_string()
  }}
}

impl AddAssign for Status {
  fn add_assign(&mut self, other: Self) {
    *self = match *self {
      Status::Opened(count) => match other {
        Status::Opened(count2) => Status::Opened(count + count2),
        _ => other,
      },
      _ => other
    }
  }
}

相关问题