Hi Folks, I'm a newby to rust and I'm very excited to learn about it, specially about avoid runtime errors! I have a C, C++, Java and Python as background, and was playing around with enums and traits and reach to this.
Suppose that I have an Enum to represent two variants and implement Add
trait to this, but I want to sum just variants of same type, and variants of different types should not be summed. In fact, different variants sum should not even allowed to compile the code. Is it possible to tell the compiler "hey check this staticaly, and if so, don't compile and warn user about it"?
enum MyEnum {
A(i8),
B(i8)
}
impl Add for MyEnum {
type Output = Self;
fn add(self, other: MyEnum) -> Self {
match (&self, other) {
(MyEnum::A(x),MyEnum::A(y)) => MyEnum::A(x+y),
(MyEnum::B(x),MyEnum::B(y)) => MyEnum::B(x+y),
_ => *self //but what I really want is in this case compiler should highlitgh an error
}
}
}
fn main() {
let var = MyEnum::A(10) + MyEnum::B(5); //I want to know if it's possible to compile to avoid this staticaly
}
I came to this because as MyEnum
variants increase, match arms will increase by 2^N. And why not to handle with Result<MyEnum, Error>
or to panic!
? Well, if compiler can check static variable definitions, why not to static check this operation with different tyes and avoid a runtime break?
Please help me to achieve this goal!
@Edit:
I clarify the situation and the example case in here: