elixir - 添加可选参数 elixir 导致函数 def 冲突
问题描述
该功能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 conflicts with defaults from hello/2
谁能解释这为什么以及如何有意义?
解决方案
def hello/1 与 hello/2 的默认值冲突
这意味着编译器不知道是否hello("foo")
意味着:
- 调用
hello/1
with"foo"
作为参数。 - 调用
hello/2
with"foo"
作为第一个参数和默认的第二个参数。
它不知道这一点,因为两者具有相同的调用语法,但是子句可以以不同的方式实现。
您可以首先使用默认值声明函数签名,然后定义使用该默认值的实现。我认为最好只定义一个返回的最终结果,并将"Hello #{name}"
该行为包装在另一个函数子句中:
def hello(user, opts \\ [])
def hello(%User{name: name}, opts), do: hello(name, opts)
def hello(name, _opts), do: "Hello #{name}"
推荐阅读
- python - 无法将文件写入本地主机和网络共享
- c# - 无法从 Visual Studio 2019 中的解决方案资源管理器中删除文件
- python - 从内存中永久删除精灵 Pygame
- json - JSON Schema 是否支持深度对象验证?
- amazon-web-services - 无法让 Mosquitto <-> AWS IoT -bridge 保持连接
- javascript - Formik - 状态和初始值被覆盖
- android - 错误:命令失败:./gradlew app:installDebug -PreactNativeDevServerPort=8081
- smartcontracts - 为什么像 signer_account_id 这样的环境变量会导致错误:ProhibitedInView?
- jquery - jQuery 日期选择器。我如何从 Jquery datepicker 中获取年份
- r - 在 R 中使用 get() 的问题 - 找不到对象(可能与环境有关?)