<!--?xml version="1.0" encoding="UTF-8" standalone="no"?--> elixir在1.2後增加了一個新的特性i helper. 在iex shell中使用i可以查看任意數據的數據類型和詳細描述 #查看變數描述 iex(1)> i {:test, " ...
elixir在1.2後增加了一個新的特性i helper. 在iex shell中使用i可以查看任意數據的數據類型和詳細描述
#查看變數描述 iex(1)> i {:test, "That sounds great"} Term {:test, "That sounds great"} Data type Tuple Reference modules Tuple #查看Module描述(有點類似於Erlang的lists:module_info) iex(2)> i List Term List Data type Atom Module bytecode usr/local/Cellar/elixir/1.2.0/bin/../lib/elixir/ebin/Elixir.List.beam Source private/tmp/elixir20160101-48495-1fg1arr/elixir-1.2.0/lib/elixir/lib/list.ex Version [322093417650371381585336045669056703278] Compile time 2016-1-1 11:57:45 Compile options [:debug_info] Description Use h(List) to access its documentation. Call List.module_info() to access metadata. Raw representation :"Elixir.List" Reference modules Module, Atom來看看這麼神奇的功能是怎麼實現的吧~ https://github.com/elixir-lang/elixir/blob/master/lib/iex/lib/iex/helpers.ex#L420
@doc """ Prints information about the given data type. """ def i(term) do info = ["Term": inspect(term)] ++ IEx.Info.info(term) for {subject, info} <- info do info = info |> to_string() |> String.strip() |> String.replace("\n", "\n ") IO.puts IEx.color(:eval_result, to_string(subject)) IO.puts IEx.color(:eval_info, " #{info}") end dont_display_result end
可以看出它只是把IEx.info.info的結果打出來,我們再看看它發生了什麼? https://github.com/elixir-lang/elixir/blob/master/lib/iex/lib/iex/info.ex
defprotocol IEx.Info do @fallback_to_any true @spec info(term) :: [{atom, String.t}] def info(term) end defimpl IEx.Info, for: Tuple do def info(_tuple) do ["Data type": "Tuple", "Reference modules": "Tuple"] end end
它是一個protocol,在這個文件中把elixir的基本類型都實現了一次,它會返回一個keyword list, 所以我們才能看到,那麼如果我們試試自己定義?
iex(3)> defmodule User do …(3)> defstruct name: "John", age: 25 …(3)> @type t :: %User{name: String.t, age: non_neg_integer} …(3)> end
因為在info.ex中已處理struct的類型, 如果我們現在直接i的結果它是
iex(4)> i %User{} Term %User{age: 25, name: "John"} Data type User Description This is a struct. Structs are maps with a __struct__ key. Reference modules User, Map
接下來, 我們來自定義看看
iex(5)> defimpl IEx.Info, for: User do …(5)> def info(item) do …(5)> ["Data type": User, "Description": "The customer is god, pleasure they", "Reference": "blablabla..."] …(5)> end …(5)> end iex(6)> i %User{} Term %User{age: 25, name: "John"} Data type Elixir.User Description The customer is god, pleasure they Reference blablabla...
成功!
官方文檔: http://elixir-lang.org/docs/stable/iex/IEx.Helpers.html#i/1
if my fingers were erlang processes