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


Elixir Access.get_and_update用法及代碼示例

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

用法:

get_and_update(container, key, fun)
@spec get_and_update(
  data,
  key(),
  (value() | nil -> {current_value, new_value :: value()} | :pop)
) ::
  {current_value, new_data :: data}
when data: container(), current_value: var

獲取並更新 container 中的給定鍵(映射、關鍵字列表、實現 Access 行為的結構)。

fun 參數接收 key 的值(或 nil 如果 key 不存在於 container 中)並且必須返回一個二元素元組 {current_value, new_value} :"get" 值 current_value (檢索到的值,可以在返回之前對其進行操作)和要存儲在key(new_value)下的新值。 fun 也可能返回 :pop ,這意味著應該從容器中刪除當前值並返回。

返回的值是一個二元素元組,其中 fun 返回的 "get" 值和 key 下具有更新值的新容器。

例子

iex> Access.get_and_update([a: 1], :a, fn current_value ->
...>   {current_value, current_value + 1}
...> end)
{1, [a: 2]}

相關用法


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