JacksonManns
JacksonManns

Reputation: 11

Perform checks on a nested enum

I have an enum which is defined as follows:

enum MyEnum {
    X(u32),
    Y(Vec<MyEnum>),
    Z(Vec<MyEnum>),
}

As you can see, the enum is nested and can have other enums of its type inside of it. I'm trying to perform a simple check: I want to check if any of the u32s is greater than 5.

I have thought about using recursion here as this seems like an inherently recursive problem but from my searches it was clear that rust doesn't support recursion or that it is not recommended that it is used. How would I go about solving this problem and performing the check?

Upvotes: 1

Views: 259

Answers (2)

Netwave
Netwave

Reputation: 42708

You can make a method over your Enum, and recursively call it:

enum MyEnum {
    X(u32),
    Y(Vec<MyEnum>),
    Z(Vec<MyEnum>),
}

impl MyEnum {
    fn greater_than(&self, x: u32) -> bool {
        match self {
            Self::X(v) => v > &x,
            Self::Y(v) | Self::Z(v) => v.iter().any(|y| y.greater_than(x)),
        }
    }
}

Playground

Upvotes: 2

yolenoyer
yolenoyer

Reputation: 9445

It is perfectly ok to use recursion in Rust, there is no particular problem about it.

In your case, you could write your check like this:

fn my_check(en: &MyEnum) -> bool {
    match en {
        MyEnum::X(n) => *n > 5,
        MyEnum::Y(v) | MyEnum::Z(v) => v.iter().any(my_check),
    }
}

Upvotes: 0

Related Questions