这是 Elixir 中非常常见的模式。最后一个参数应该是一个列表(具体的关键字列表)并且默认为[]。在 Elixir 中,如果最后一个参数是关键字列表,则无需在列表周围添加 []s。例如:
def do_lots(arg1, arg2, opts \\ []) do
one = opts[:one] || :default
two = opts[:two] # default to nil if it's not passed
# do something with arg1, arg2, one, and two
end
def my_func do
arg1
|> do_lots(2)
|> do_lots(49, one: :question)
|> do_lots(99, two: :agent)
|> do_lots(-1, one: 3, two: 4)
end
处理可变大小参数的另一个选项是将它们全部作为列表传递。这使得函数 arity 1 并且您可以根据需要处理它们。
最后,您可以将部分或全部参数作为映射传递。这样做的好处是允许您在映射上进行模式匹配并根据映射中传递的键创建多个函数子句。
请记住,您不能轻易地在关键字列表上进行模式匹配,因为它们取决于顺序。