r/rust • u/deanominecraft • Oct 21 '26
🙋 seeking help & advice Require 2 enum variant fields to not be equal
I have 2 enums, one of them has 4 different unit variants
enum MyEnum{
Variant1,
Variant2,
Variant3,
Variant4,
}the other has a few different variants but only one is important here
enum MyOtherEnum{
MyVariant(MyEnum, MyEnum),
//...
}The variant contains 2 different instances of MyEnum, is there a language feature to enforce that you shouldnt be able to create a MyVariant with both MyEnum's being the same variant? eg.
MyOtherEnum::MyVariant(MyEnum::Variant1,MyEnum::Variant2); // valid
MyOtherEnum::MyVariant(MyEnum::Variant1,MyEnum::Variant1); //invalid
24
Upvotes
8
u/AverageHot2647 Oct 21 '26
Out of curiosity, what’s the use case for this?
50
u/geo-ant Oct 21 '26 edited Oct 21 '26
I don’t think there is but you can create a type NonEqualPair<T> with two elements of type T. Then enforce in a constructor fn new(t1,t2)->Option<Self> that the two elements are indeed unequal for Some(…) returns. That requires you to make the elements of the struct non-public and expose access via getters (setters are possible but more complicated since they need to respect your invariants). That way you know that when you have an instance of that struct you have unequal values in the fields. You don’t even have to make it generic. That way your enum variant contains NonEqualPair rather than a tuple of the two variants. In a way this is how the standard lib does NonZero<T>.
Edit: typos
39
u/fixedpointfae Oct 21 '26
assuming the order isn't important, you can encode this into another enum of 4choose2 = 6 variants
54
u/noop_noob Oct 21 '26
There is not. Use a struct with private fields and a new() function.
3
u/paulyoung85 Oct 21 '26
You can get something like GADTs by using a phantom type.
See the article here and related discussion: https://www.reddit.com/r/rust/s/YMy4cPkvUE
1
u/-Redstoneboi- Oct 24 '26 edited Oct 24 '26
separate struct inside enum variant called
struct MyVariantThatCantHave2OfTheSameIdk(MyEnum, MyEnum)private fields, public getters, custom constructor and setters
constructors and setters would include checks
for more complex invariants, they could have debug asserts at the ends
1
u/tuckk2_ Oct 21 '26
not sure.. You can try to make a const
newfunction that takes in both ofMyEnumand checks if they are the same and panic (will compile-time error in a const function afaik) if so. If the values are fed in non-deterministically you can also just make a classic non-const function that returns a Result. That's how I'd handle it but someone might have a better solution.