[英]How do I avoid syntax repitition when matching enums?
I have a struct in which one of the fields is an enum, and when using a match statement there is a lot of repetition that feels avoidable.我有一个结构,其中一个字段是一个枚举,当使用匹配语句时,有很多重复感觉是可以避免的。
Basically what I have now is基本上我现在拥有的是
match self.foo // which is an enum, Foo {
Foo::Bar => something,
Foo::Bazz => something else,
_ => you get the point
}
I tried:我试过了:
match self.foo {
Foo::{
Bar => something,
Bazz => something else,
}
}
but did not have the intended effect.但没有达到预期的效果。 Is it possible to not have to retype Foo:: every time or is it just something I need to live with?
是否有可能不必每次都重新输入 Foo:: ,或者这只是我需要忍受的东西?
You can use the use Foo::*;
您可以使用
use Foo::*;
statement to bring all the variants of Foo
into scope:将
Foo
的所有变体带入 scope 的语句:
enum Foo {
Bar,
Bazz,
}
fn main() {
let foo = Foo::Bar;
use Foo::*;
match foo {
Bar => println!("something"),
Bazz => println!("something else"),
}
}
You can import the names of enum variants to use them directly:您可以导入枚举变体的名称以直接使用它们:
use Foo::*;
match self.foo {
Bar => something,
Bazz => something else,
}
This is how None
and Some
work without needing Option::
before them.这就是
None
和Some
在不需要Option::
之前工作的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.