Destructure vector field of a struct

I'd like to know if it is possible to destruct a field of a struct with Vec type. For example:

struct Node {
    pub v: i32,
    pub children: Vec<Node>,
}
 
let tree = Node {
    v: 1,
    children: vec![Node { v: 2, children: vec![] }],
};

// Is it possible to do this?
match tree {
    Node {
        v,
        children: vec![a @ Node {..}]
    }
}

I don't think it's possible to match it in one go, but you can pull the Vec out and match it as a slice in a guard, like:

match tree {
    Node {
        v,
        children,
    } if matches!(children[..], [Node { v: 2, .. }]) => {
        // do stuff
     }
}

Though if you need a, that'll require a sub-match.

2 Likes

Or use a view struct.

2 Likes

Thanks, this is amazing!

Looks this approach cannot handle mutual recursion.