如何将字典传递给带有关键字参数的函数?

How to pass a Dict to a function with Keyword arguments?

假设我有这个 Dict:

d=Dict("arg1"=>10,"arg2"=>20)

和这样的函数:

function foo(;arg1,arg2,arg3,arg4,arg5)
  #Do something
end

如何调用函数并将 Dict d 中的参数作为函数的参数传递? 我知道我可以做到:

foo(arg1=d["arg1"],arg2=d["arg2"])

但是有什么方法可以自动执行此操作吗?我的意思是找出在 Dict 中定义了哪些参数并将其自动传递给函数的方法。

Symbol键的字典可以直接splat加入函数调用:

julia> d = Dict(:arg1 => 10, :arg2 => 12)
Dict{Symbol, Int64} with 2 entries:
  :arg1 => 10
  :arg2 => 12

julia> f(; arg1, arg2) = arg1 + arg2
f (generic function with 1 method)

julia> f(; d...)
22

注意函数调用中的分号,它确保 d 中的元素被解释为关键字参数而不是恰好是 Pairs.

的位置参数