elixir - 什么是Elixir Bang函数?

标签 elixir phoenix-framework

在阅读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/

相关文章:

elixir - Rails 引擎就像 Phoenix

postgresql - Elixir 和 hex 更新后无法构建 Phoenix 项目

binary - 以可变数量填充 elixir 中的二进制文件

elixir - Phoenix Framework/Elixir,输出相对文件路径到控制台

postgresql - Ecto Postgres安装报错密码验证失败

elixir - 在Elixir/Mix/Phoenix应用中将服务/初始化代码放在哪里?

email - 如何使用 Bamboo with Phoenix 修复 'render/2 is undefined' 错误

elixir - 升级 Elixir 后出现 "Phoenix.HTML.Engine.init/1 is undefined or private"和 "Plug.Conn.__struct__/1 is undefined"等错误

hex - Elixir mix 自动确认

elixir - 无法在 Windows 上生成 Phoenix 应用程序