|>运算符称为管道运算符。可以把函数调用串联起来,使前一个函数调用返回的值作为第一个实参传给下一个函数调用。
String.replace_suffix(String.upcase(String.duplicate("go ", 3)), " ", "!")
# versus
"go "
|> String.duplicate(3)
|> String.upcase()
|> String.replace_suffix(" ", "!")
也可以写成一行:
"go " |> String.duplicate(3) |> String.upcase() |> String.replace_suffix(" ", "!")
Kernel函数通常在各处使用时不带Kernel模块名,但在管道链中使用这些函数时,就需要写出模块名。例如,2 * 3 == 6也可以写成:
2 |> Kernel.*(3) |> Kernel.==(6)
何时使用管道运算符、何时不用,取决于个人偏好。有些 Elixir 开发者喜欢遵循以下规则:
只进行一次函数调用时,不要使用管道运算符。
# do
String.split("hello", "")
# don't
"hello" |> String.split("")
不要在管道链中直接创建匿名函数。
# do
take_n_letters = fn n -> Enum.take(?a..?z, n) end
2 |> Kernel.*(3) |> take_n_letters.()
# don't
2 |> Kernel.*(3) |> (fn n -> Enum.take(?a..?z, n) end).()
管道链始终要以变量或字面量开头,而不是函数调用。
# do
"hello" |> String.upcase() |> String.split("")
# don't
String.upcase("hello") |> String.split("")