"match_unchecked"? Zero cost enum field access, like a union

Hello,

Is there a way to use unsafe to tell the compiler to treat an enum as a specific variant without the check & branch? Same idea as accessing the fields of a union, but for an enum?

I spent a bit of time reading around and couldn't find exactly what I'm looking for. Maybe I just don't know the right search terms. I found people using transmute to accomplish this but that seems like a heavy hammer with the potential for a lot of collateral UB.

Thanks for any thoughts.

You can use unreachable_unchecked. The check will be optimized away.

let MyEnum::MyVariant(x) = y else {
    unreachable_unchecked();
};

Option and Result also implements unwrap_unchecked using unreachable_unchecked.

2 Likes

Also, rust does have unions if you want them.

1 Like

Brilliant! I think that does exactly what I'm looking for.

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.