【问题标题】:Elixir: Pattern match with multiple map match optionsElixir:具有多个地图匹配选项的模式匹配
【发布时间】:2020-05-15 20:04:45
【问题描述】:

在 Elixir 中,而不是像这样写:

case getUser(id) do
  %User{status: "pending"} -> something()
  %User{status: "available"} -> something()
  _ -> something_else()
end

我把它简化成:

case getUser(id) do
  %User{status: "pending" | "available"} -> something()
  _ -> something_else()
end

但出现错误:

cannot find or invoke local |/2 inside match. Only macros can be invoked in a match and they must be defined before their invocation. Called as: "pending" | "available"

有没有更好的方法来做到这一点?我不想把同一个函数写两次。

【问题讨论】:

  • 请修改您的代码以对结构使用大括号。发布的内容甚至无法编译。
  • 谢谢,我已经编辑了 - 输入时出错。

标签: phoenix-framework elixir


【解决方案1】:
case getUser(id) do
  %User{status: status} when status in ["pending", "available"] -> something()
  _ -> something_else()
end

when .. inGuard,并在 case, cond, and if 页面上简要提及。

【讨论】:

  • status in ~w|pending available| :)
猜你喜欢
  • 1970-01-01
  • 2017-05-14
  • 2021-06-13
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
相关资源
最近更新 更多