我如何在Elixir函数中使用匹配的参数 [英] How do I used matched arguments in elixir functions
本文介绍了我如何在Elixir函数中使用匹配的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有一个函数的两个用例。对有订阅的用户进行处理,对没有订阅的用户进行处理。
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.
和
def add_subscription(subscription_id, user)
我该如何进行模式匹配
谢谢!
推荐答案
您可以将函数参数绑定到变量:
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})
这篇关于我如何在Elixir函数中使用匹配的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文