Reputation: 1017
Suppose I have an enum
:
enum Foobar {
Foo(i32),
Bar(f64)
}
I also have a function that takes a Foobar
as an argument:
fn foo(x: &mut Foobar) {
match x {
Foobar::Foo(i32) => { /* do something */ },
Foobar::Bar(f64) => { /* panic */ }
}
}
Is it possible to throw a compile time error if the caller of the function passes the Bar
variant to the function, without using a compiler plugin?
Upvotes: 3
Views: 956
Reputation: 58975
No.
Even a compiler plugin (by which I assume you mean a "lint") can't possibly cover all cases.
If you want to make it statically impossible to pass a particular piece of data to the function, then change the types so that it's actually not valid: define a sibling of Foobar
that doesn't have the Bar
variant, along with some conversions between the two.
There is no simple or automatic way to do this in Rust; you'll just have to do the hard yakka. Or wait for refinement types, but I wouldn't recommend doing that.
Upvotes: 4