當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Elixir Access.at用法及代碼示例


Elixir語言中 Access.at 相關用法介紹如下。

用法:

at(index)
@spec at(integer()) :: access_fun(data :: list(), current_value :: term())

返回一個函數,該函數訪問列表的index(從零開始)處的元素。

返回的函數通常作為訪問器傳遞給 Kernel.get_in/2 Kernel.get_and_update_in/3 和朋友。

例子

iex> list = [%{name: "john"}, %{name: "mary"}]
iex> get_in(list, [Access.at(1), :name])
"mary"
iex> get_in(list, [Access.at(-1), :name])
"mary"
iex> get_and_update_in(list, [Access.at(0), :name], fn prev ->
...>   {prev, String.upcase(prev)}
...> end)
{"john", [%{name: "JOHN"}, %{name: "mary"}]}
iex> get_and_update_in(list, [Access.at(-1), :name], fn prev ->
...>   {prev, String.upcase(prev)}
...> end)
{"mary", [%{name: "john"}, %{name: "MARY"}]}

at/1 也可用於從列表中彈出元素或列表中的鍵:

iex> list = [%{name: "john"}, %{name: "mary"}]
iex> pop_in(list, [Access.at(0)])
{%{name: "john"}, [%{name: "mary"}]}
iex> pop_in(list, [Access.at(0), :name])
{"john", [%{}, %{name: "mary"}]}

當索引超出範圍時,返回 nil 並且永遠不會調用更新函數:

iex> list = [%{name: "john"}, %{name: "mary"}]
iex> get_in(list, [Access.at(10), :name])
nil
iex> get_and_update_in(list, [Access.at(10), :name], fn prev ->
...>   {prev, String.upcase(prev)}
...> end)
{nil, [%{name: "john"}, %{name: "mary"}]}

如果訪問的結構不是列表,則會引發錯誤:

iex> get_in(%{}, [Access.at(1)])
** (RuntimeError) Access.at/1 expected a list, got: %{}

相關用法


注:本文由純淨天空篩選整理自elixir-lang.org大神的英文原創作品 Access.at(index)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。