gpt4 book ai didi

elixir - 通过添加可选参数 elixir 实现函数 def 冲突

转载 作者:行者123 更新时间:2023-12-02 19:51:26 25 4
gpt4 key购买 nike

hello 函数没有任何冲突并且工作正常。

defmodule User do
defstruct [:name]
end

defmodule Greeter do
def hello(%User{} = user) do
"Hello #{user.name}"
end

def hello(name) do
"Hello #{name}"
end
end

但是如果我向第一个函数添加可选参数,我会得到冲突错误。

...
def hello(%User{} = user, opts \\ []) do
"Hello #{user.name}"
end
...

错误def hello/1 与 hello/2 的默认值冲突

谁能解释这是为什么以及如何有意义?

最佳答案

def hello/1 conflicts with defaults from hello/2

这意味着编译器不知道 hello("foo") 是否意味着:

  • "foo" 作为参数调用 hello/1
  • 使用 "foo" 作为第一个参数和默认的第二个参数调用 hello/2

它不知道这一点,因为两者具有相同的调用语法,但子句的实现可能不同。

您可以先声明具有默认值的函数签名,然后定义使用该默认值的实现。我认为最好只定义返回 "Hello #{name}" 的最终结果,并将该行为包装在另一个函数子句中:

def hello(user, opts \\ [])
def hello(%User{name: name}, opts), do: hello(name, opts)
def hello(name, _opts), do: "Hello #{name}"

关于elixir - 通过添加可选参数 elixir 实现函数 def 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58095078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com