Elixir 长生不老药
我不确定如何最好地做到这一点: 我有一个函数可以查找IP并返回它来自的国家Elixir 长生不老药,elixir,phoenix-framework,Elixir,Phoenix Framework,我不确定如何最好地做到这一点: 我有一个函数可以查找IP并返回它来自的国家 country = Geolix.lookup(remote_ip).country.registered_country.name 有时它会失败,在这种情况下,没有定义任何数组键 在其他语言中,我可能会这样做: try do country = Geolix.lookup(remote_ip).country.registered_country.name rescue country = nil end
country = Geolix.lookup(remote_ip).country.registered_country.name
有时它会失败,在这种情况下,没有定义任何数组键
在其他语言中,我可能会这样做:
try do
country = Geolix.lookup(remote_ip).country.registered_country.name
rescue
country = nil
end
我真的在努力让语法正确。这也感觉不太“干净”;有更好的方法吗?您不需要使用
试试宏。它不是为控制流量而设计的
我建议使用:
country =
with %{country: country} <- Geolix.lookup(remote_ip),
%{registered_country: rc} <- country,
%{name: name} <- rc, do: name
FWIW,以下是正确的语法:
country =
try do
Geolix.lookup(remote_ip).country.registered_country.name
rescue
_ -> nil
end
@m3characters提供的答案也很好。您不需要使用try
宏来实现这一点。它不是为控制流量而设计的
我建议使用:
country =
with %{country: country} <- Geolix.lookup(remote_ip),
%{registered_country: rc} <- country,
%{name: name} <- rc, do: name
FWIW,以下是正确的语法:
country =
try do
Geolix.lookup(remote_ip).country.registered_country.name
rescue
_ -> nil
end
@m3characters提供的答案也很好。您也可以使用case。。。使用模式匹配执行
,如果案例
的结果具有您需要的所有键,则它与第一个匹配,在第一个匹配中提取名称,如果不匹配,则表示从Geolix.lookup/1
获得的内容与您想要的模式不符,并返回nil
country =
case Geolix.lookup(remote_ip) do
%{country: %{registered_country: %{name: name}}} -> name
_ -> nil
end
您还可以使用case。。。使用模式匹配执行
,如果案例
的结果具有您需要的所有键,则它与第一个匹配,在第一个匹配中提取名称,如果不匹配,则表示从Geolix.lookup/1
获得的内容与您想要的模式不符,并返回nil
country =
case Geolix.lookup(remote_ip) do
%{country: %{registered_country: %{name: name}}} -> name
_ -> nil
end
我真的很喜欢。有趣的是,我想出了两种不同的答案,两种答案都不那么明确。@AlekseiMatiushkin yeap我看到你的答案突然出现,然后因为你没有展示这个答案,我决定写它-我发现模式匹配是我的最爱之一,因为它是多么明确(而且容易增长/改变)!这是一篇很有趣的帖子。我想这是我比较喜欢的方式,读起来很简单谢谢你们两位的贡献!:)我真的很喜欢。有趣的是,我想出了两种不同的答案,两种答案都不那么明确。@AlekseiMatiushkin yeap我看到你的答案突然出现,然后因为你没有展示这个答案,我决定写它-我发现模式匹配是我的最爱之一,因为它是多么明确(而且容易增长/改变)!这是一篇很有趣的帖子。我想这是我比较喜欢的方式,读起来很简单谢谢你们两位的贡献!:)