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


Elixir Module.get_attribute用法及代碼示例

Elixir語言中 Module.get_attribute 相關用法介紹如下。

用法:

get_attribute(module, key, default \\ nil)
@spec get_attribute(module(), atom(), term()) :: term()

從模塊中獲取給定的屬性。

如果屬性用 accumulate Module.register_attribute/3 標記,則始終返回一個列表。如果屬性沒有用accumulate 標記並且沒有設置為任何值,則返回nil

@ 宏編譯為對該函數的調用。例如,下麵的代碼:

@foo

擴展為類似於:

Module.get_attribute(__MODULE__, :foo)

該函數隻能在尚未編譯的模塊上使用。使用 Module.__info__/1 回調獲取所有持久屬性,或使用 Code.fetch_docs/1 檢索已編譯模塊中的所有文檔相關屬性。

例子

defmodule Foo do
  Module.put_attribute(__MODULE__, :value, 1)
  Module.get_attribute(__MODULE__, :value) #=> 1

  Module.get_attribute(__MODULE__, :value, :default) #=> 1
  Module.get_attribute(__MODULE__, :not_found, :default) #=> :default

  Module.register_attribute(__MODULE__, :value, accumulate: true)
  Module.put_attribute(__MODULE__, :value, 1)
  Module.get_attribute(__MODULE__, :value) #=> [1]
end

相關用法


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