2

My program receives commands from the user in the form of numbers: let command: int. That command is supposed to be one of enum values:

enum Command {
    Launch,
    Stop,
}

How do I convert the command integer to a Command enum? Once I've converted the type from integer to enum, how do I exhaustively match that enum and handle the possibility that command's value is beyond the Command's range of values? Look at the code:

match command { // command has `enum Command` type here already
    Launch => { /* ... */ }
    Stop => { /* ... */ }
    _ => { /* ... */ } // command is user input, so it can have any value, but Rust will yell "unreachable pattern" here
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
  • *command's value is beyond the Command's range of values* — that's not possible, once you've converted the number to the enum. That's rather one of the *points* of having an enum. – Shepmaster Nov 11 '19 at 15:52
  • 1
    @Shepmaster First of all, thank you for pointing to the existing answer (the funny thing I've seen it, but didn't realize it was exact same case as mine). Also, yes, you're correct, I just meant the situation when the value will not match the type. Anyway, thanks! Solved! – Nurbol Alpysbayev Nov 11 '19 at 15:56
  • @Shepmaster also, I appreciate the edits, they are on point, improved my English skills a bit :-) – Nurbol Alpysbayev Nov 11 '19 at 15:59
  • 1
    Sure thing! I'd point specifically to [my answer](https://stackoverflow.com/a/57578431/155423) as I think it's the most idiomatic and up-to-date of the answers. The key thing is that the out-of-bounds error is handled, it's just handled when converting to the enum, not afterwards. – Shepmaster Nov 11 '19 at 16:01

0 Answers0