Mahesh Bansod
Mahesh Bansod

Reputation: 2033

How to enforce that all variants of an enum can be returned from a function

I'm implementing the trait FromStr for an enum, and I want to make sure that I'm covering all variants of the enum. Is there a way to tell Rust to throw a compile-time error if some enum variants are not returned by the function?
For example, I don't want the code below to compile since the variants E::b and E::c are not returned by any path.

fn from_str(s: &str) -> Result<Self, Self::Error> {
    match s {
        "a" => Ok(E::a),
        _ => Err("no"),
    }
}
enum E {
    a,
    b,
    c,
}

I'm looking for a more general solution than just for implementing the FromStr trait since I plan to use a similar pattern for other functions as well.

Upvotes: 0

Views: 846

Answers (1)

at54321
at54321

Reputation: 11756

There is no way to make the Rust compiler enforce that (apart from what PitaJ suggested in a comment - a dead code warning for variants that have never been constructed, but it's clear that "trick" wouldn't work in most real-world cases).

However, there are multiple crates that can do that string-to-variant conversion for you. One such crate is strum_macros. It provides the EnumString macro, which seems exactly like what you want.

Not only will such a macro guarantee you haven't forgotten a variant, but you will also avoid the need to write quite a bit of boilerplate code.

Upvotes: 2

Related Questions