rustenums

Rust: name fields in enum


Is it possible to name or somehow else describe the fields of an enum in Rust?

Let's look at this code:

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

It might not be obvious what each of those values mean, in this case the first piece is my piece that captures the second piece and thereby moves from the first position ((i8, i8)) to the second.

Ideal would be something like this:

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

which sadly doesn't work.

Is there any way I can make my enum more descriptive (besides comments)?


Solution

  • You can use embedded structs like:

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

    Or even better, take them outside, where you can implement methods over them and then embedded it in you enum:

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