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"),
}
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"),
}
}
}
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"),
}
I am guessing it was possible before unique vectors got removed? Or am I missing some magic using ref
that can solve this?
Pattern matching and enums can be used for a number of things, like error handling, handling null values, and more. In this article, we will go over the basics of pattern matching, enums, and see how enums can be used with pattern matching, including:
You can reference enum variants using ::. For e.g., to instantiate a Player who has a paid account: It’s also possible to add data to enum variants. For e.g.: Option<T> and Result<T,E> are widely used enum s and are part of the Rust standard library.
But the variants of an enum are fixed and defined within the enum itself. You can instantiate multiple instances of a Player. But let’s look at a type that is a little more niche. Imagine you have only two account types — a free and a paid one. You can use an enum to represent this concept.
That means the base enum itself cannot be assigned to a variable. For an example of an enum, let’s create a vehicle enum with three variants: Car, MotorCycle, and Bicycle. We can then access the variants by writing Vehicle::<variant>: And, if you want to statically type it, you can write something like this:
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With