Assign a bool (true) value using: a) enum and b) if statement

I want to create a 'bool variable' from / using a) enum and b) if statement.
I am expecting in the code below a true value: 'whereYouLive' should be assigned to a true value.
Instead - I get message: you might have meant to use one of the enum's variants.
What am I doing wrong?

fn main() {
  #[derive(Debug)]
  enum Planets {
    Sun = 0,
    Earth,
  }
  let whereYouLive = Planets::Earth; /* assign Earth to the whereYouLive variable */
  let liveInEarth =
    if whereYouLive == Planets.Earth {
      true
    } else {
      false
    };
}

I think you meant to type if whereYouLive == Planets::Earth....

I get error: error[E0369]: binary operation == cannot be applied to type Planets

Ok - read the very helpful error explanation - I just must educate myself some more - thank you!

ote: an implementation of `PartialEq<_>` might be missing for `Planets`
 --> src/main.rs:3:3
  |
3 |   enum Planets {
  |   ^^^^^^^^^^^^ must implement `PartialEq<_>`
help: consider annotating `Planets` with `#[derive(PartialEq)]`
  |
3 |   #[derive(PartialEq)]
  |

For more information about this error, try `rustc --explain E0369`.

Not pretty but...

#[derive(Debug)]
enum Planets {
    Sun = 0,
    Earth,
}

fn main() {
    let where_i_live = Planets::Earth;
    let i_live_in_earth = matches!(where_i_live, Planets::Earth);
    println!("I live in earth is {}", i_live_in_earth);

    let where_you_live = Planets::Sun; // Weird planet
    let you_live_in_earth = matches!(where_you_live, Planets::Earth);
    println!("You live in earth is {}", you_live_in_earth);
}

Playground.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.