如何对包装字符串的枚举变体进行模式匹配? [英] How to pattern-match against an enum variant that wraps a String?
本文介绍了如何对包装字符串的枚举变体进行模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个枚举:
enum T {
A(String),
}
我想匹配这个枚举的一个变量,但这段代码不起作用:
I want to match a variable of this enum, but this code doesn't work:
match t {
T::A("a") => println!("a"),
T::A("b") => println!("b"),
_ => println!("something else"),
}
我知道我可以做到这一点,但在我看来它太冗长了:
I understand that I can do this, but it is so verbose in my opinion:
match t {
T::A(value) => match value.as_ref() {
"a" => println!("a"),
"b" => println!("b"),
_ => println!("something else"),
},
}
有没有更短的方法来做到这一点?
Is there a shorter way to do this?
推荐答案
我认为唯一的另一种方法是使用 匹配保护,但这与您的嵌套匹配版本一样冗长.
The only other way I think would be to use a match guard, but this is about as verbose as your version with nested matches.
match t {
T::A(ref value) if value == "a" => println!("a"),
T::A(ref value) if value == "b" => println!("b"),
_ => println!("something else"),
}
这篇关于如何对包装字符串的枚举变体进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文