'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?



Solution 1:[1]

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

Solution 2:[2]

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),
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Netwave
Solution 2 yolenoyer