MLmuchAmaze
MLmuchAmaze

Reputation: 499

Wild card and destructuring of enums in Rust

Is it possible to wild card the variants of an enum, while still caputing its associated data?

enum BAR {
    BAR1,
    BAR2,
}

enum BAZ {
    BAZ1,
    BAZ2,
    BAZ3,
}

enum FOO {
    FOO1(BAR, BAZ),
    FOO2(BAR, BAZ),
    FOO3(BAR, BAZ),
    //...
}

impl FOO {
    pub fn getBar(&self) -> &BAR {
        return match self {
            FOO::FOO1(bar, _) => bar,
            // _(bar, _) => bar,
        }
    }
}

The enum FOO has over 50 variants. The line FOO::FOO1(bar, _) => bar, does what I need, but it would be quite ugly to list all 50 variants, where all arms essentially look the same. Is there some form of _(bar, _) => bar, where the variants are being wild carded but the associated data is still retrievable?

Upvotes: 2

Views: 359

Answers (1)

Masklinn
Masklinn

Reputation: 42302

Is there some form of _(bar, _) => bar, where the variants are being wild carded but the associated data is still retrievable?

No. You can achieve this via a macro, that's about it.

But I've got to say I'm questioning your structure: if you have "over 50 variants" all with exactly the same associated data why is it not a structure with 3 fields?

struct Foo {
    discriminant: Whatever,
    bar: Baz,
    baz: Baz,
}

This is exactly equivalent to what you have on your hands, except it's not a pain in the ass to access bar and baz.

Upvotes: 8

Related Questions