Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pattern-match a Vec<T> inside an enum field without nesting matches?

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?

like image 656
oli_obk Avatar asked Mar 04 '15 10:03

oli_obk


People also ask

What are enums and pattern matching in Java?

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:

How to add data to enum variants in rust?

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.

Can you have multiple variants of an enum type?

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.

Why can't I assign an enum to a variable?

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:


1 Answers

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>.

like image 97
huon Avatar answered Sep 30 '22 14:09

huon