本文介绍了以变​​量为键的地图上的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

如何在具有字符串键的地图上进行模式匹配?

How can I do pattern matching on a map which has a string key?

iex(1)> my_map = %{"key1" => "var1"}
%{"key1" => "var1"}
iex(2)> %{aa => bb} = my_map
** (CompileError) iex:2: illegal use of variable aa inside map key match, maps can only match on existing variable by using ^aa
    (stdlib) lists.erl:1354: :lists.mapfoldl/3
iex(2)> %{"aa" => bb} = my_map
** (MatchError) no match of right hand side value: %{"key1" => "var1"}


推荐答案

如果保证地图具有仅1个条目(如您在评论中阐明的),您可以将其传递给,然后对结果进行模式匹配:

If the Map is guaranteed to have only 1 entry (like you clarified in the comments), you can pass it to Map.to_list/1 and then pattern match on the result:

iex(1)> my_map = %{"key1" => "var1"}
%{"key1" => "var1"}
iex(2)> [{key, value}] = Map.to_list(my_map)
[{"key1", "var1"}]
iex(3)> key
"key1"
iex(4)> value
"var1"

这篇关于以变​​量为键的地图上的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-09 01:01