获取elixir中的所有参数和关键字参数
elixir是否有办法从一个函数中获取所有参数和关键字参数,并将它们发送到另一个函数 比如:获取elixir中的所有参数和关键字参数,elixir,Elixir,elixir是否有办法从一个函数中获取所有参数和关键字参数,并将它们发送到另一个函数 比如: def func1("test", 10) do ... end def func2("test", "string", "another string", 10) do ... end def check(type, *args, **kwargs) do case type do :func1 -> func1(*args, **kwargs) :func2 -
def func1("test", 10) do
...
end
def func2("test", "string", "another string", 10) do
...
end
def check(type, *args, **kwargs) do
case type do
:func1 -> func1(*args, **kwargs)
:func2 -> func2(*args, **kwargs)
end
end
check(:func1, "test", 10)
check(:func2, "test", "string", "another string", 10)
注意func1和func2现在可能有相同数量的参数
在python中,您可以使用**kwargs和*args来实现这一点,我不确定elixir是否有类似的功能elixir不支持参数数量可变的函数。您所能做的最好是在
check
中接受参数列表,并使用apply
将其动态传递给函数:
def check(type, args) do
case type do
:func1 -> apply(__MODULE__, :func1, args)
:func2 -> apply(__MODULE__, :func2, args)
end
end
您现在可以这样调用检查:
check(:func1, [:foo, :bar, baz: :quux])
它将在内部调用:
func1(:foo, :bar, baz: :quux)
Elixir不支持参数数目可变的函数。您所能做的最好是在check
中接受参数列表,并使用apply
将其动态传递给函数:
def check(type, args) do
case type do
:func1 -> apply(__MODULE__, :func1, args)
:func2 -> apply(__MODULE__, :func2, args)
end
end
您现在可以这样调用检查:
check(:func1, [:foo, :bar, baz: :quux])
它将在内部调用:
func1(:foo, :bar, baz: :quux)