elixir - 5. match 操作符
访问量: 1380
参考:https://elixir-lang.org/getting-started/pattern-matching.html
= 不但是赋值的,还是用来做match 操作的
> x = 1
> 1= x #=> true
可以对变量进行赋值:
iex(29)> {a, b, c} = {:a, 2, "c"}
{:a, 2, "c"}
iex(30)> a
:a
iex(31)> b
2
iex(32)> c
"c"
^操作符(pin operator) 可以为已经存在的变量重新赋值(还是赋原来的值, 不清楚为什么这么设计)
iex> x = 1
1
iex> ^x = 2
** (MatchError) no match of right hand side value: 2
iex> {y, ^x} = {2, 1}
{2, 1}
iex> y
2
iex> {y, ^x} = {2, 2}
** (MatchError) no match of right hand side value: {2, 2}
也可以使用| 来进行匹配赋值:
> [a | _] = [1,23,4,5,6]
[1, 23, 4, 5, 6]
iex(36)> a
1
注意,上面的 _ 被舍弃了。 下面这样却可以:
> [a | b] = [1,23,4,5,6]
[1, 23, 4, 5, 6]
iex(38)> b
[23, 4, 5, 6]