Ensure an Enum is Always a Specific Variant

I have an enum, it looks like this:

pub enum Boop {
    Here(...),
    There(...),
    // ...
}

I have some other code, it looks like this:

fn do_something(boop: Boop) {
    // ...
    let Boop(here) = match boop { Here(h) => h, panic("Not a 'Here'") };
    // alternatively:
    // if let Boop::Here(h) = here { /* ... */ } else { panic!("Not a 'Here'") }
    // ...
}

The thing is, the Boop passed to do_something should always be the variant Boop::Here - if it's anything else, there is something wrong with the code itself, wherein a panic is justified. However, this doesn't feel like idiomatic code. Would there be a more idiomatic way or general method to do the above? Is it possible to check that boop is always a Boop::Here?

TL;DR: How do you ensure that an enum is always a specific variant?

i don't think this is possible using a static check. you could let do_something take whatever the inner part of Here ist, so it would be upon the caller to check that (assuming that Here and There have different types in them). Alternatively, you could make do_something return a Result, which becomes an Error in case boop is a There.

2 Likes

One way to enforce this statically is by changing your enum to something like:

struct Here { ... }

pub enum Boop {
    Here(Here),
    There(...),
    // ...
}

Then only implementing do_something on Here

4 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.