Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir 长生不老药_Elixir_Phoenix Framework - Fatal编程技术网

Elixir 长生不老药

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

我不确定如何最好地做到这一点:

我有一个函数可以查找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 =
  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我看到你的答案突然出现,然后因为你没有展示这个答案,我决定写它-我发现模式匹配是我的最爱之一,因为它是多么明确(而且容易增长/改变)!这是一篇很有趣的帖子。我想这是我比较喜欢的方式,读起来很简单谢谢你们两位的贡献!:)