Convert from number to enum

enum Test {
    A,
    B,
}

fn convert(n: u8) -> Test {
    todo!();
}

Write a match. And you'll probably want to return Option<Test> or something because there are numbers which are not valid in that enum.

3 Likes

In situations like this I normally use the num_derive crate to generate from_u8() and to_u8() methods which do the match @scottmcm is talking about. That way you don't accidentally forget to update the match when you add a new variant to Test.

1 Like