struct是一種用戶自定義的映射,其中包含了默認的項目。函數
┃ defmodule User do ┃ defstruct name: nil, age: nil ┃ end
能夠,它們會在編譯時被執行ui
┃ defmodule User do ┃ defstruct name: nil, age: 10 + 11 ┃ end
能夠講field name以原子列表的形式表示code
┃ defmodule Post do ┃ defstruct [:title, :content, :author] ┃ end
使用@derive 屬性get
┃ defmodule User do ┃ @derive [MyProtocol] ┃ defstruct name: nil, age: 10 + 11 ┃ end ┃ ┃ MyProtocol.call(john) #=> works
使用@enforce_keys 屬性it
┃ defmodule User do ┃ @enforce_keys [:name] ┃ defstruct name: nil, age: 10 + 11 ┃ end
┃ %User{age: 21} ┃ ** (ArgumentError) the following keys must also be given when building struct User: [:name]
注意,這隻在編譯時管用。不能用於validation。io
容許在爲函數編寫@spec時以User.t 的形式表示該結構體編譯
┃ defmodule User do ┃ defstruct name: "John", age: 25 ┃ @type t :: %User{name: String.t, age: non_neg_integer} ┃ end