在阅读Phoenix教程时(在Incoming Events部分中),我首先注意到带有尾随感叹号/ bang(!)的函数。
def handle_in("new_msg", %{"body" => body}, socket) do
broadcast! socket, "new_msg", %{body: body}
{:noreply, socket}
end
尾随的感叹号是什么意思?它有什么作用吗? 我一直在搜索并尝试查找,但不确定使用的术语是否正确。到目前为止,似乎仅作为约定的功能在失败时会引发错误,但始终总是这样。
我唯一看到的提及出现在Dave Thomas的“Programming Elixir”中:
Identifiers in Elixir are combinations of upper and lower case ASCII
characters, digits, and underscores. Function names may end with a
question mark or an exclamation point.
在the documentation中也提到:
Notice that when the file does not exist, the version with ! raises an
error. The version without ! is preferred when you want to handle
different outcomes using pattern matching...
这些都不解释这是否是其他讽刺者或炼金术士的约定或任何其他用途。请帮忙。
最佳答案
这个:
Notice that when the file does not exist, the version with ! raises an error. The version without ! is preferred when you want to handle different outcomes using pattern matching...
如果您查看源代码,将会更加清楚。函数名称中的
!
符号只是语法上的约定。如果看到名称中包含!
符号的函数,则意味着可能存在一个具有相同名称但没有!
符号的函数。这两个函数将执行相同的操作,但是它们将以不同的方式处理错误。没有
!
的函数只会向您返回错误。您将需要知道错误的类型并根据您的类型来处理它。查看broadcast/3
函数(不带!
的variant): def broadcast(server, topic, message) when is_atom(server),
do: call(server, :broadcast, [:none, topic, message])
它只是调用给定的服务器,并将返回其结果。
broadcast!/3
函数将执行相同的操作,但是:它会在不使用broadcast
的情况下调用!
函数,将检查其结果并提高BroadcastError
exception: def broadcast!(server, topic, message) do
case broadcast(server, topic, message) do
:ok -> :ok
{:error, reason} -> raise BroadcastError, message: reason
end
end
关于elixir - 什么是Elixir Bang函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324302/