【ELIXIR】struct的应用

什么是struct?

struct是一种用户自定义的映射,其中包含了默认的项目。函数

如何定义struct?

┃ defmodule User do
┃   defstruct name: nil, age: nil
┃ end

能够在struct定义中执行语句吗?

能够,它们会在编译时被执行ui

┃ defmodule User do
┃   defstruct name: nil, age: 10 + 11
┃ end

如何快捷建立struct?

能够讲field name以原子列表的形式表示code

┃ defmodule Post do
┃   defstruct [:title, :content, :author]
┃ end

如何为struct实现协议?

使用@derive 属性get

┃ defmodule User do
┃   @derive [MyProtocol]
┃   defstruct name: nil, age: 10 + 11
┃ end
┃ 
┃ MyProtocol.call(john) #=> works

如何让某个key成为必填的?

使用@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

@type属性有什么用

容许在为函数编写@spec时以User.t 的形式表示该结构体编译

┃ defmodule User do
┃   defstruct name: "John", age: 25
┃   @type t :: %User{name: String.t, age: non_neg_integer}
┃ end
相关文章
相关标签/搜索