I would like to perform an operation all variants of an enum.
Currently this requires quite long winded code like
enum Number{
One(i64),
Two(i64),
Three(i64),
Four(i64)
}
fn do_stuff() {
match self {
Number::One(n) =>
blah(n),
Number::Two(n) =>
blah(n),
Number::Three(n) =>
blah(n),
Number::Four(n) =>
blah(n)
}
}
In this case, blah would be a generic method which handles all of the
variants of Number
. Now I know this can't be avoided in rust, but I
was wondering whether it could at least be written once. My thought
was something like this:
impl Number {
fn apply<F, T, R>(&self, f: F) -> R
where F: Fn(impl T) -> R,
{
match self {
Number::One(n) =>
f(n),
Number::Two(n) =>
f(n),
Number::Three(n) =>
f(n),
Number::Four(n) =>
f(n)
}
}
}
The point here is that I could write this once when I define my data
structure (Number
). The in downstream code, I should be able to do
something like:
trait Foo {
fn frob(&self) -> T;
}
impl Foo for i64 {
fn from(&self) -> Result<(),String>{
Ok(())
}
}
fn do_foo(n:Number) -> Result<(), String> {
n.apply(|n| n.from())
}
Of course, I would still need to write the underlying implementation
for each of the types wrapped in the enum (which wouldn't be i64 and
might not all be the same), but I wouldn't have to write the enum
dispatch functionality everytime.
Nice idea, but fails because I can't do impl T
where T
is some
trait because Rust is unhappy that T is generic.
Is there a solution here?