什么是struct?
struct是一种用户自定义的映射,其中包含了默认的项目。
如何定义struct?
┃ defmodule User do
┃ defstruct name: nil, age: nil
┃ end
可以在struct定义中执行语句吗?
可以,它们会在编译时被执行
┃ defmodule User do
┃ defstruct name: nil, age: 10 + 11
┃ end
如何快捷创建struct?
可以讲field name以原子列表的形式表示
┃ defmodule Post do
┃ defstruct [:title, :content, :author]
┃ end
如何为struct实现协议?
使用@derive 属性
┃ defmodule User do
┃ @derive [MyProtocol]
┃ defstruct name: nil, age: 10 + 11
┃ end
┃
┃ MyProtocol.call(john) #=> works
如何让某个key成为必填的?
使用@enforce_keys 属性
┃ 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。
@type属性有什么用
允许在为函数编写@spec时以User.t 的形式表示该结构体
┃ defmodule User do
┃ defstruct name: "John", age: 25
┃ @type t :: %User{name: String.t, age: non_neg_integer}
┃ end