Reputation: 7937
I have enum with variants with value:
enum Foobar<T, G> {
Foo,
Bar(T),
Baz(G),
}
I have a piece of code where I need to match enum value, but I don't want to destruct it.
fn foobar<T, G, F1, F2>(value: Foobar<T, G>, f1: F1, f2: F2) -> bool
where
F1: Fn(T) -> bool,
F2: Fn(G),
{
let res = match value {
Foobar::Foo => true,
Foobar::Bar(v) => f1(v),
Foobar::Baz => false,
};
if let Foobar::Baz(v2) = value {
f2(v2);
}
res
}
It won't compile because expected unit struct, unit variant or constant, found tuple variant Foobar::Baz
I don't want to cange it to Foobar::Baz(_)
because it will force Copy trait on G
, and I don't want it.
My example is a bit artificial, but let's assume I need to keep separate call to f2
.
Is there a way to match an enum variant without destructing it?
Upvotes: 1
Views: 3207
Reputation: 58875
You can't.
But it wouldn't help anyway. The problem is that value
is not available after the match
because you (might have) moved data from it into f1
.
You can fix it by reorganising the code a little, so that you only look at Baz
when the value from Bar
has not been moved:
fn foobar<T, G, F1, F2>(value: Foobar<T, G>, f1: F1, f2: F2) -> bool
where
F1: Fn(T) -> bool,
F2: Fn(G),
{
let res = match value {
Foobar::Foo => true,
Foobar::Bar(v) => f1(v),
Foobar::Baz(v2) => {
f2(v2);
false
},
};
res
}
Upvotes: 2