Reputation: 1070
Say I have two use cases for a function. Do something with users that have a subscription and something with users that don't have a subscriptions.
def add_subscription(subscription_id, %User{subscription: nil})
# Do something with user here.
And
def add_subscription(subscription_id, user)
How do I do pattern matching like this and also still use the user in the first function?
Thanks!
Upvotes: 5
Views: 1562
Reputation: 84140
You can bind the function argument to a variable:
def add_subscription(subscription_id, %User{subscription: nil} = user)
The convention is to assign after the pattern match:
# Do This
def foo(%User{subscription: nil} = user)
# Instead of this
def foo(user = %User{subscription: nil})
Upvotes: 11