Elixir 别名
2023-12-15 14:27 更新
alias允许你为任何具名模块赋予别名.想象一下我们的Math模块要使用一个特殊的列表执行方法来做特定的数学操作:
defmodule Math do
alias Math.List, as: List
end从现在起,任何提到List的地方都会自动扩展成Math.List.如果有人想访问原始的List,就需要在之前加上模块名Elixir.:
List.flatten #=> uses Math.List.flatten
Elixir.List.flatten #=> uses List.flatten
Elixir.Math.List.flatten #=> uses Math.List.flatten
所有在Elixir中定义的模块,都定义在一个主要Elixir命名空间中.为了方便,在调用它们时你可以省略"Elixir".
别名经常用于定义缩写.事实上,调用alias时不带:as,就会自动将模块名的最后部分设为别名.例如:
alias Math.List
等同于
alias Math.List, as: List注意alias确定了语法范围,能让你在特定的函数中设置别名:
defmodule Math do
def plus(a, b) do
alias Math.List
# ...
end
def minus(a, b) do
# ...
end
end在上述例子中,由于我们是在plus/2函数中调用的alias,所以别名只在函数plus/2中可用.对minus/2没有影响.
以上内容是否对您有帮助:

免费 AI IDE


更多建议: