[Solved] How to assign an integer value to an enum type variable?


#1
enum RangeType {
    StartEnd = 0,
    Start = 1,
    End = 2,
    Illegal = 3,
}

struct Range {
    kind: RangeType,
    start: Option<u64>,
    end: Option<u64>,
}

fn get_range(req: &String) -> Option<Range> {
    // [&str, &str]
    let bytes: Vec<&str> = /code here/;
    let start = bytes[0].parse::<u64>();
    let end = bytes[1].parse::<u64>();
   
    let n1 = match start {
        Ok(i) => 1,
        Err(e) => 3
    };
    let n2 = match end {
        Ok(i) => -1,
        Err(e) => 0
    };
    let kind: RangeType = n1 + n2;

    Some(Range {
        kind: kind,
        start: Some(123),
        end: Some(456),
    })
}

I want to make these code let kind: RangeType = n1 + n2; work like the C code below. Is it possible?

enum TEST {A, B, C};
enum TEST var1 = 0;
enum TEST var2 = 1 + 1;
printf("%d %d\n", var1 == A, var2 == C);

#2

It’s possible using std::mem::transmute but highly discouraged. Is there a reason you want to do it this way apart from C code being like that?


#3

I just do not want to write too many if else :sweat_smile:


#4

You can do something like this, which doesn’t seem onerous, is more robust (compiler will ensure your match is exhaustive if you were to ever change things), and clearer (to me, at least):

let kind = match (start, end) {
        (Ok(_), Ok(_)) => RangeType::StartEnd,
        (Err(_), Err(_)) => RangeType::Illegal,
        (Ok(_), Err(_)) => RangeType::Start,
        (Err(_), Ok(_)) => RangeType::End,
    };

#5

It’s very clear. Thank you :grinning:


#6

Using an enum this way feels kinda… odd. You usually use an enum as an algebraic datatype (i.e. I have an X or a Y or a Z), so using + to join them doesn’t usually make sense. What exactly do you want the let kind: RangeType = n1 + n2 to do?

As another thing, it looks like your get_range() function could be better expressed by implementing the FromStr trait on Range. This also means you can do something like let range: Range = some_str.parse()?, which is a more idiomatic way of doing things.


#7

n1 + n2 is 0 or 1 or 2 or 3, correspond to StartEnd and Start and End and Illegal, respectively. So, I think let kind: RangeType = n1 + n2 will get an enum value (StartEnd or Start or End or Illegal) from an integer value like C language. But I am wrong.