Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust: name fields in enum

Tags:

enums

rust

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)?

like image 468
Teiem Avatar asked Nov 22 '25 22:11

Teiem


1 Answers

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

like image 175
Netwave Avatar answered Nov 26 '25 16:11

Netwave