How to use consistent arguments in elixir functions

Let's say I have two options for using a function. Do something with users who have a subscription, and something with users who don't have a subscription.

def add_subscription(subscription_id, %User{subscription: nil})
  # Do something with user here.

AND

def add_subscription(subscription_id, user)

How do I perform pattern matching like this, and also use the user in the first function?

Thank!

+3
source share
1 answer

You can bind a function argument to a variable:

def add_subscription(subscription_id, %User{subscription: nil} = user)

The agreement is assigned after conformance to the template:

# Do This
def foo(%User{subscription: nil} = user)

# Instead of this
def foo(user = %User{subscription: nil})
+10
source

Source: https://habr.com/ru/post/1668399/


All Articles