Tic Tac Toe Winner Match Lines

Check every winning line of a tic tac toe board with index triples and a guard, because repeated bindings in one arm are illegal.

RustData Integrity

Code

rustsnippet
30 lines
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"),
        }
    }
}

Reading the code — Tic Tac Toe Winner Match Lines

The file’s story is carried by the functions winner and main, doing all the work.

A single loop drives the file — for &(a, b, c) in &LINES. match here is the control flow: arms enumerate the value’s shapes exhaustively.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Using it

Entry signature: fn winner(board: &[char; 9]) -> Option<char>

main calls 1 helper in sequence: winner.

Key statements

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"),
}

Interactive Tools for This Topic

FAQ

How do you run Tic Tac Toe Winner Match Lines?
This is a complete program, not a library excerpt — execution starts at the top.