簡體   English   中英

如何從 Elixir 中的 ETS 返回一個值?

[英]How to return one value from ETS in Elixir?

我有具有如下鍵值方案的 ETS 表:

users = :ets.tab2list(:users)
IO.inspect users # printing

[
{"3eadd68495d",
%UserType{
 name: "John",
 id: "3eadd68495d",
 status: "Free"
}},
{"234a34495d",
%UserType{
 name: "Steve",
 id: "234a34495d",
 status: "Free"
}},
{"9add68495d",
%UserType{
 name: "Mike",
 id: "9add68495d",
 status: "Busy"
}}
]

我想獲得狀態為“免費”的任何元素的一個 id。

我已經嘗試使用循環獲得價值

users = :ets.tab2list(:users)
for user <- users do
   userValue = user |> elem(1)
   if userValue.status === "Free" do
     userValue.id
   end
end

但它返回多個 id 值(3eadd68495d234a34495d),而不是一個

if userValue.status === "Free" do userValue.id之后我需要像 "break" 這樣的東西,但我不知道如何在 Elixir 中使用它。

對於單個值,應該使用Enum.reduce_while/3

Enum.reduce_while(users, nil, fn
  {_, %UserType{status: "Free", id: id}}, _ -> {:halt, id}
  _, acc -> {:cont, acc}
end)

或者正如@sabiwara 在評論中指出的那樣,使用Enum.find_value/2


我不建議這樣做,但可以try/catch來“打破” for理解,如下所示。

try do
  for {_, %UserType{status: "Free", id: id}} <- users, do: throw(id)
catch
  id -> id
end

旁注:一般來說,它的效率極低,一旦你已經擁有ETS ,你最好使用:ets.select/2 ,如https://write.as/yuriploc/ets-dets-match-patterns-and中所述-規格

在以下幾行旁邊應該做的

:ets.select(
  :users,
  [{{:_, %{status: :"$1", id: :"$2"}},
   [{:"==", :"$1", "Free"}],
   [:"$2"]}])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM