如何模式匹配Vec< T>在没有嵌套匹配的枚举区域内? [英] How can I pattern-match a Vec<T> inside an enum field without nesting matches?
问题描述
模式匹配 Vec
可以通过使用& v [..]
或 v.as_slice()
。
Pattern-matching a Vec<T>
can be done by using either &v[..]
or v.as_slice()
.
let x = vec![1, 2, 3];
match &x[..] {
[] => println!("empty"),
[_] => println!("one"),
[..] => println!("many"),
}
如果我有一个字段的枚举包含我想要匹配的 Vec
,我需要在外部匹配手段中创建一个嵌套的匹配:
If I have an enum with a field that contains the Vec
I want to match on, I need to create a nested match inside the outer match arm:
enum Test {
Many(Vec<u8>),
Text(String),
}
fn main() {
let x = Test::Many(vec![1, 2, 3]);
match x {
Test::Text(s) => println!("{}", s),
Test::Many(v) => match &v[..] {
[] => println!("empty"),
[_] => println!("one"),
[..] => println!("many"),
}
}
}
我想要做的是直接匹配 Vec
,如下例所示:
What I would like to be able to do, is to match directly on the Vec
as in the following example:
match x {
Test::Text(s) => println!("{}", s),
Test::Many([]) => println!("empty"),
Test::Many([_]) => println!("one"),
Test::Many([..]) => println!("many"),
}
我猜,一个href =https://github.com/rust-lang/rust/pull/12244/files#diff-ca04b724f2df29e92436ba8d2e09e18bL12 =nofollow>唯一的矢量被删除?或者我使用可以解决这个问题的 ref
缺少一些魔法。
I am guessing it was possible before unique vectors got removed? Or am I missing some magic using ref
that can solve this?
推荐答案
Deref 模式,这将允许通过实现 Deref
的任何类型的模式匹配或 DerefMut
,例如可以在框< T>
中的 T
上匹配,或者在 [T ]
insidea Vec< T>
。
It's not possible to do this directly, unfortunately. However, there is desire to possibly add "Deref
patterns", which would allow pattern matching through any types which implement Deref
or DerefMut
, e.g. one could match on the T
inside a Box<T>
, or on the [T]
"inside" a Vec<T>
.
这篇关于如何模式匹配Vec< T>在没有嵌套匹配的枚举区域内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!