In Elixir, I'd like to pattern match for the presence of a field in a struct - either where the field is not nil, or even better, where it is a string.
I know how pattern match a struct where the field is nil. For example:
def run(%Query{expression: nil})
How can I match structs where the given field is any string?
You can match with:
Kernel.match?("" <> rest , "")
#true
def run(%Query{expression: "" <> expression})
Or you can use a guard for this:
Kernel.match?(foo when is_binary(foo), nil)
#false
def run(%Query{expression: expression}) when is_binary(expression)
A list of valid guard clauses is available at http://elixir-lang.org/getting-started/case-cond-and-if.html#expressions-in-guard-clauses
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With