Joel Jackson
Joel Jackson

Reputation: 1070

How do I used matched arguments in elixir functions

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

Answers (1)

Gazler
Gazler

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

Related Questions