You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elixir中Enum.find触发Access.get/3函数子句匹配错误的排查与解决

错误原因分析

你调用Enum.find(data, ...)时,data是一个Map,Enum遍历Map时会把每个键值对作为元组(比如{"items", [...]}, {"paging", %{}})传入回调函数。而你在回调里用location["id"]尝试访问元组的"id"键,元组并不支持这种Access操作,所以触发了FunctionClauseError——因为Access.get/3没有处理元组+字符串键的函数子句。

正确解法

要提取指定id的条目,应该先获取data["items"]这个列表,再对列表使用Enum.find:

location_id = 32_000_007
Enum.find(data["items"], fn location -> location["id"] == location_id end)

这段代码会返回匹配的条目:

%{
  "countryCode" => "AF",
  "id" => 32000007,
  "isCountry" => true,
  "name" => "Afghanistan"
}

如果需要处理data["items"]可能为nil的情况(比如接口返回异常),可以加上默认值避免报错:

Enum.find(data["items"] || [], fn location -> location["id"] == location_id end)

内容的提问来源于stack exchange,提问作者Beate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 02:01:19