← 中文资源

简体中文版本

match 井字棋获胜线加 guard

用下标三元组枚举井字棋全部获胜线,match 配 guard 判三连:同一臂里重复绑定不合法,先绑三个名字再用 guard 收紧才是标准解法。

阅读英文原文

实现说明

活动部件是函数 winner、main。 本示例的循环部分是 for &(a, b, c) in &LINES。match 一条一条覆盖值的形态——不会意外落到默认分支上。

使用要点

  • 执行文件,main 会按顺序走完 winner。

常见问题

「match 井字棋获胜线加 guard」这个示例怎么运行?

文件自包含:直接运行,没有需要预先安装的依赖。

主签名形如 fn winner(board: &[char; 9]) -> Option<char>

核心语句

match (board[a], board[b], board[c]) {
    // repeated bindings are illegal in one arm, so bind three names
    // and use a guard to require all three equal and non-empty
    (p, q, r) if p == q && q == r && p != ' ' => return Some(p),
    _ => continue,
}
match winner(board) {
    Some(p) => println!("{name}: {p} wins"),
    None => println!("{name}: still open"),
}

代码示例

fn winner(board: &[char; 9]) -> Option<char> {
    // tic tac toe: every winning line as index triples into the flat board
    const LINES: [(usize, usize, usize); 8] = [
        (0, 1, 2), (3, 4, 5), (6, 7, 8), // rows
        (0, 3, 6), (1, 4, 7), (2, 5, 8), // columns
        (0, 4, 8), (2, 4, 6),            // diagonals
    ];
    for &(a, b, c) in &LINES {
        match (board[a], board[b], board[c]) {
            // repeated bindings are illegal in one arm, so bind three names
            // and use a guard to require all three equal and non-empty
            (p, q, r) if p == q && q == r && p != ' ' => return Some(p),
            _ => continue,
        }
    }
    None
}

fn main() {
    let x_wins: [char; 9] = ['x', 'x', 'x', 'o', 'o', ' ', ' ', ' ', ' '];
    let o_wins: [char; 9] = ['x', 'o', 'x', 'x', 'o', ' ', ' ', 'o', ' '];
    let playing: [char; 9] = ['x', 'o', 'x', 'o', 'x', 'o', 'o', 'x', ' '];

    for (name, board) in [("x wins", &x_wins), ("o wins", &o_wins), ("playing", &playing)] {
        match winner(board) {
            Some(p) => println!("{name}: {p} wins"),
            None => println!("{name}: still open"),
        }
    }
}