简体   繁体   中英

Problems with Rust Enum

I can't seem to get my Match Expression to work. Looking at it, It seems the same as other examples I've looked at.

fn draw(board: BoardType) {
    let board = match board{
        BoardType::B3x3(board, _) => board,
        BoardType::B4x4(board, _) => board
    };
}

#[derive(Debug)]
enum BoardType {
    B3x3([[Space; 3]; 3], (i8, i8)),
    B4x4([[Space; 4]; 4], (i8, i8)),
}

#[derive(Copy, Clone, Debug)]
enum Space {
    Blank,
    X,
    O,
    Blocked,
}
BoardType::B4x4(board,_) => board
                            ^^^^^ expected an array with a fixed size of 3 elements, found one with 4 elements

I don't really understand why this isn't working.

match expressions return a value. Even though you are not using that value in this code, the compiler needs to type-check the expression. However the two branches of the expression have different types: [[Space; 3]; 3] [[Space; 3]; 3] [[Space; 3]; 3] and [[Space; 4]; 4] [[Space; 4]; 4] [[Space; 4]; 4] respectively.

The error message is telling you that it expects the second branch to have the same type as the first.

Part of your problem is likely that your code is too simple, and isn't actually doing anything. Suppose you had functions for drawing these boards:

fn draw_3x3(board: [[Space; 3]; 3]) {
    unimplemented!()
}

fn draw_4x4(board: [[Space; 4]; 4]) {
    unimplemented!()
}

Then, when you use them, the branches will both have the same type ( () ), so the whole expression will type-check:

fn draw(board: BoardType) {
    let board = match board{
        BoardType::B3x3(board, _) => draw_3x3(board),
        BoardType::B4x4(board, _) => draw_4x4(board),
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM