I have an enum
with an associated show
function.
enum Foo {
Bar(u32),
Baz
}
fn show(foo: Foo) {
match foo {
Foo::Bar(_) => show_bar(foo),
Foo::Baz => show_baz(foo),
}
}
Based on the variant, a specialized show_*
function is called.
fn show_bar(foo: Foo) {
match foo {
Foo::Bar(x) => println!("BAR({x})"),
_ => (),
}
}
fn show_baz(foo: Foo) {
match foo {
Foo::Baz => println!("BAZ"),
_ => (),
}
}
Since I can't pass variants as types, I need to repeat the match foo
pattern matching inside each show_*
function, which is a bit verbose and undeeded.
Is there a better / more idiomatic way to do this?
I'm a fairly simple soul and not a Rust expert, so maybe this doesn't meet your needs for some reason - but why not simply pass the associated data? (Which is nothing in the case of Baz
)
enum Foo {
Bar(u32),
Baz
}
fn show(foo: Foo) {
match foo {
Foo::Bar(barValue) => show_bar(barValue),
Foo::Baz => show_baz(),
}
}
fn show_bar(x: u32) {
println!("BAR({x})"),
}
fn show_baz() {
println!("BAZ"),
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.