darko
darko

Reputation: 321

How can I pattern match on this?

I have this expression:

obj1 = Repo.get_by(Struct1, var1: "123")

How can I pattern match on it so that it checks if a record exists and if its field "var2" is nil. Is it possible to do a pattern match on that at all?

For now I'm doing this:

  cond obj1 do
    obj11  && (obj11.var2 == nil) -> #....
    true -> # doesn't exist or var2 isn't nil
  end

Upvotes: 1

Views: 151

Answers (1)

Dogbert
Dogbert

Reputation: 222398

You can use the pattern %Struct1{var2: nil}:

case Repo.get_by(Struct1, var1: "123") do
  %Struct1{var2: nil} -> #...
  _ -> #...
end

Upvotes: 5

Related Questions