maps,Elixir 中的主要键值存储,有一个有趣的功能,在模式匹配方面将它们与其他数据结构区分开来。
map 实际上可以仅对值的子集进行模式匹配。模式中的键必须存在于匹配中,但两个结构不必像 list 或 tuple 那样相互镜像。例如:
iex(1)> [a, b] = [1, 2, 3]
** (MatchError) no match of right hand side value: [1, 2, 3]
iex(1)> {a, b} = {1, 2, 3}
** (MatchError) no match of right hand side value: {1, 2, 3}
iex(1)> %{:a => one} = %{:a => 1, :b => 2, :c =>3}
%{a: 1, b: 2, c: 3}
iex(2)> one
1
iex(3)> %{:a => one, :c => three} = %{:a => 1, :b => 2, :c =>3}
%{a: 1, b: 2, c: 3}
iex(4)> three
3
iex(5)> one
1
iex(6)> %{} = %{:a => 1, :b => 2, :c =>3}
%{a: 1, b: 2, c: 3}
iex(7)> %{:d => four} = %{:a => 1, :b => 2, :c =>3}
** (MatchError) no match of right hand side value: %{a: 1, b: 2, c: 3}
iex(8)> %{:a => one, :d => four} = %{:a => 1, :b => 2, :c =>3}
** (MatchError) no match of right hand side value: %{a: 1, b: 2, c: 3}
如果模式的数据结构与匹配的数据结构(即大小)不同,我们可以看到list 和tuple 都不匹配。而地图并非如此。因为模式和匹配中都存在密钥,所以匹配成功,无论模式和匹配的大小不同。空的map 也会匹配。
但是,如果模式中的键不在匹配中,则匹配不会成功。即使有匹配的键也是如此。因此,模式中使用的任何键都必须存在于匹配中。
您将在 Phoenix 框架中广泛看到这种匹配,以仅从请求中获取必要的参数。
来源:-Notes on Elixir: Pattern-Matching Maps