【问题标题】:rust name fields in enum枚举中的锈名称字段
【发布时间】:2022-01-16 00:32:44
【问题描述】:

是否可以命名或以其他方式描述 rust 中 enum 的字段?
让我们看看这段代码

enum Move {
    Capture(Piece, Piece, (i8, i8), (i8, i8)),
    ...
}

每个值的含义可能并不明显,在这种情况下,第一个片段是我的片段,它捕获了第二个片段,从而从第一个位置 ((i8, i8)) 移动到第二个位置。

理想的应该是这样的

enum Move {
    Capture(piece: Piece, captured: Piece, from: (i8, i8), to: (i8, i8)),
    ...
}

遗憾的是,这不起作用。

有什么方法可以让我的enum 更具描述性(cmets 除外)?

【问题讨论】:

  • 是的,你可以!只需使用大括号 {} 而不是括号。
  • Capture(...) 更改为Capture { ... }
  • 我有一些像 getToPosition 这样只关心 to 的辅助函数,是否可以选择使用类 c 枚举结构忽略匹配中的所有其他字段?
  • 使用.. 忽略所有其他字段:Capture { to, .. }

标签: rust enums


【解决方案1】:

您可以使用嵌入式结构,例如:

enum Move {
    Capture{piece: Piece, captured: Piece, from: (i8, i8), to: (i8, i8)},
    ...
}

或者更好的是,把它们带到外面,在那里你可以对它们实现方法,然后将它嵌入到你的枚举中:

struct Capture{piece: Piece, captured: Piece, from: (i8, i8), to: (i8, i8)};

impl Capture {
    ...
}

enum Move {
    Capture(Capture),
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    相关资源
    最近更新 更多