skip to Main Content

I have code something like this.

#[derive(PartialEq)]
enum FALUDA {
    Juice,
    Ice,
}

let a: u32 = 0;

if a == FALUDA::Juice {
 //Yay
}

If I try this code I am getting below error.

78 |     if a                 == FALUDA::Juice {
   |        --------             ^^^^^^^^^^^^^ expected `u32`, found `FALUDA`
   |        |
   |        expected because this is `u32`

I dont want to cast.

2

Answers


  1. You need to cast the enum value to u32 (the type of a).

    Here is a complete example:

    #[derive(PartialEq)]
    enum FALUDA {
        Juice,
        Ice,
    }
    
    fn main() {
        let a: u32 = 0;
        if a == FALUDA::Juice as u32 {
            print!("Juicy")
        }
    }
    

    For simple cases casting really is all one should need. But if you need to do a lot of conversions from/to enum values, you might consider using a crate, such as strum_macros.

    Login or Signup to reply.
  2. Can we achieve something with match?

    Yes, you can implement PartialEq<FALUDA> for u32:

    #[derive(PartialEq)]
    enum FALUDA {
        Juice,
        Ice,
    }
    
    impl PartialEq<FALUDA> for u32 {
        fn eq(&self, rhs: &FALUDA) -> bool {
            match rhs {
                FALUDA::Juice => self == &0,
                FALUDA::Ice => self == &1,
            }
        }
    }
    
    fn main() {
        let a: u32 = 0;
    
        if a == FALUDA::Juice {
            println!("Yay");
        }
    }
    

    But this may prove unstable if you’d decide to change the order of FALUDA‘s variants.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search