当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。