#Matching on enums

15 messages · Page 1 of 1 (latest)

upbeat frost
#

Hi, I have an enum like this

pub enum Complicated {
  Boolean(bool),
  Integer(i32),
  ArrayOfInteger(Vec<i32>)
}

And a method

fn is_boolean(&self, v: &Complicated)->bool{
  // I want to check if v is of type boolean or not
  // here
}

how do I complete the is_boolean function? Also I need to implement is_integer and is_array_of_integer method.

remote gyro
#

You can use matches! for that:

matches!(self, Complicated::Boolean(_))
```https://doc.rust-lang.org/std/macro.matches.html
upbeat frost
#

Thanks. I forgot about the _ operator.

#

That indeed makes this question beginner level xD

upbeat frost
#

is there any possible way to get the value from v ?

#

without using match everytime?

remote gyro
#

What's v, actually? I didn't notice that before.

#

Are you comparing two Complicateds?

upbeat frost
#

yes,

#

I think I can use if let Complicated::Boolean(value)=v {// here value should be available}?

remote gyro
#

Yes that's true.

upbeat frost
#

cool. last question is this a good practice to have nested if let?

fn has_positive_integer(&self, key: &str) -> bool {
        if let Some(v) = self.map_key_values.get(key) {
            if let &ParametersValue::INTEGER(value) = v {
                return value > 0;
            }
            false
        } else {
            false
        }
    }
remote gyro
#

You can put them in the same pattern:

fn has_positive_integer(&self, key: &str) -> bool {
  if let Some(&ParametersValue::INTEGER(value)) = self.map_key_values.get(key) {
    value > 0
  } else {
    false
  }
}
upbeat frost
#

ohh. wow. this looks much clean.

#

Thanks for the help.