1

How do I match against a nested String in Rust? Suppose I have an enum like

pub enum TypeExpr {
    Ident((String, Span)),
    // other variants...
}

and a value lhs of type &Box<TypeExpr>. How do I check whether it is an Ident with the value "float"?

I tried

if let TypeExpr::Ident(("float", lhs_span)) = **lhs {}

but this doesn't work since TypeExpr contains a String, not a &str. I tried every variation of the pattern I could think of, but nothing seems to work.

Antimony
  • 37,781
  • 10
  • 100
  • 107
  • 2
    Does this answer your question? [How to pattern-match against an enum variant that wraps a String?](https://stackoverflow.com/questions/49075255/how-to-pattern-match-against-an-enum-variant-that-wraps-a-string) – Sven Marnach Sep 21 '20 at 07:20

1 Answers1

1

If you really want to do this with an if let, you might have to do it like this

if let TypeExpr::Ident((lhs_name, lhs_span)) = lhs {
    if lhs_name == "float" {
        // Do the things
    }
}

Of course, it can also be done with a match:

match lhs {
    TypeExpr::Ident((lhs_name, lhs_span)) if lhs_name == "float" => {
        // Do the things
    }
    _ => {}
}
Brendan Molloy
  • 1,784
  • 14
  • 22
  • The problem with the nested if version is that it means duplicating the else code. But the pattern match with guard approach looks like it might work. Thanks! I just wish there were a nicer way to do it. – Antimony Sep 22 '20 at 14:27
  • Yeah, I know that feeling. I had to do something similar to this in a project where I was generating an AST. In general, my pattern is to use enums as much as possible, and avoid Boxing them, to make pattern matching as seamless as I can make it. This is sometimes infeasible, so we do what we must. :) – Brendan Molloy Sep 23 '20 at 09:21
  • The problem is that you need boxing with a recursive tree. – Antimony Sep 23 '20 at 16:25
  • Yes, though there are nested matching techniques to work around that, it's just annoying if you like to pattern match. – Brendan Molloy Sep 24 '20 at 10:40