一个永远循环且永不终止的函数的返回类型为no_return()(该返回类型也用于总是抛出异常的函数,如自定义错误函数,如果不指定该返回类型,Dialyzer会告诉你该函数“没有本地返回”)。 Erlang参考手册的Types and Function Specifications章节中提到了这一点: Erlang中的一些函数不是要返回的;这可能是因为它们定义了服务器,也可能是因为它们用于引发异常,如以下函数所示:
defmodule TypeSpecExamples do
@moduledoc """
Examples of typespecs using no_return and none.
"""
@spec forever :: no_return
def forever do
forever()
end
@spec only_for_side_effects :: no_return
def only_for_side_effects do
IO.puts "only_for_side_effects"
:useless_return_value # delete this line to return the value of the previous line
end
@spec print_dont_care :: no_return
def print_dont_care do
IO.puts("""
A no_return function that does not loop always returns a value, \
which can be anything, such as the atom #{only_for_side_effects()}
""")
end
@spec always_crash :: none
def always_crash do
raise "boom!"
end
@spec value_or_crash(boolean) :: number | none
def value_or_crash(b) do
if b do
1
else
raise "boom!"
end
end
end
2条答案
按热度按时间qaxu7uf21#
一个永远循环且永不终止的函数的返回类型为
no_return()
(该返回类型也用于总是抛出异常的函数,如自定义错误函数,如果不指定该返回类型,Dialyzer会告诉你该函数“没有本地返回”)。Erlang参考手册的Types and Function Specifications章节中提到了这一点:
Erlang中的一些函数不是要返回的;这可能是因为它们定义了服务器,也可能是因为它们用于引发异常,如以下函数所示:
对于这样的函数,建议通过以下形式的契约,使用特殊的
no_return()
类型作为它们的“返回”:pftdvrlh2#
下面的例子是用Elixir编写的,但我相信它们也使用了
no_return
和none
的类型规范,这对Erlangers来说也很清楚: