Elixir:具有多个地图匹配选项的模式匹配
Elixir: Pattern match with multiple map match options
在 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"
有更好的方法吗?我不想把同一个函数写两次。
case getUser(id) do
%User{status: status} when status in ["pending", "available"] -> something()
_ -> something_else()
end
when .. in
是一个 Guard and is mentioned briefly on the case, cond, and if 页面。
在 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"
有更好的方法吗?我不想把同一个函数写两次。
case getUser(id) do
%User{status: status} when status in ["pending", "available"] -> something()
_ -> something_else()
end
when .. in
是一个 Guard and is mentioned briefly on the case, cond, and if 页面。