How do I used matched arguments in elixir functions

扶醉桌前 提交于 2019-12-21 05:07:29

问题


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!


回答1:


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})


来源:https://stackoverflow.com/questions/36184062/how-do-i-used-matched-arguments-in-elixir-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!