美文网首页
Elixir-组合

Elixir-组合

作者: 你期待的花开 | 来源:发表于2018-11-14 17:36 被阅读6次

模块

模块是把函数组织到不同命名空间的最好的办法,除了能为函数分组,他还允许我们定义命名函数和私有函数。

defmodule Example do
  def greeting(name) do
    "Hello #{name}."
  end
end

iex> Example.greeting "Sean"
"Hello Sean."

Elixir 也允许嵌套的模块,这让你可以轻松定义多层命名空间:

defmodule Example.Greetings do
  def morning(name) do
    "Good morning #{name}."
  end

  def evening(name) do
    "Good night #{name}."
  end
end

iex> Example.Greetings.morning "Sean"
"Good morning Sean."

模块属性

模块的属性通常被用作常量。

defmodule Example do
  @greeting "Hello"

  def greeting(name) do
    ~s(#{@greeting} #{name}.)
  end
end

iex>Example.greeting('world')
"Hello world."

需要注意有些属性是保留的,最常用到的三个为:

  • moduledoc 当前模块的文档
  • doc 函数和宏的文档
  • behaviour 使用 OTP 或者用户定义的行为

结构体

结构体是字典的特殊形式,他们的键是预定义的,一般都有默认值。结构体必须定义在某个模块内部,因此也必须通过模块的命名空间来访问。在一个模块里只定义一个结构体是一种常用的手法。
要定义结构体,我们使用 defstruct 关键字,后面跟着关键字列表和默认值。

defmodule Example.User do
  defstruct name: "Sean", roles: []
end

# 创建结构体
iex> %Example.User{}
%Example.User{name: "Sean", roles: []}

iex> %Example.User{name: "Steve"}
%Example.User{name: "Steve", roles: []}

iex> %Example.User{name: "Steve", roles: [:admin, :owner]}
%Example.User{name: "Steve", roles: [:admin, :owner]}

我们可以像图一样更新结构体。

iex> steve = %Example.User{name: "Steve", roles: [:admin, :owner]}
%Example.User{name: "Steve", roles: [:admin, :owner]}
iex> sean = %{steve | name: "Sean"}
%Example.User{name: "Sean", roles: [:admin, :owner]}

结构体可以匹配图

iex> %{name: "Sean"} = sean
%Example.User{name: "Sean", roles: [:admin, :owner]}

相关文章

  • Elixir-组合

    模块 模块是把函数组织到不同命名空间的最好的办法,除了能为函数分组,他还允许我们定义命名函数和私有函数。 Elix...

  • Elixir-函数

    目录 匿名函数& 操作符 模式匹配 命名函数函数名字和元数私有函数卫兵参数默认值 匿名函数 匿名函数就是没有名字,...

  • Elixir-推导

    在 Elixir 中,列表推导是循环遍历枚举值的语法糖。 基础 推导经常用来根据 Enum 和 Stream生...

  • Elixir-并发

    Elixir 的一大卖点就是对并发的支持,得益于 Erlang VM (BEAM) ,Elixir 的并发要比预期...

  • Elixir-基础

    安装 在https://elixir-lang.org 上可以找到安装说明。 使用 elixir -v 查看 el...

  • Elixir-集合

    列表、元组、关键字列表(keywords)、图(maps)、字典和函数组合子(combinators) 目录 列表...

  • Elixir-魔符

    Elixir 提供了一种叫做 魔符的语法糖来标识和处理字面量。一个魔符已~开头然后接上一个字符。Elixir 已经...

  • Elixir-模式匹配

    模式匹配是 Elixir 很强大的特性,它允许我们匹配简单值、数据结构、甚至函数。 匹配操作符 Elixir 中,...

  • Elixir-控制语句

    if 和 unless 你之前可能遇到过 if/2了,如果你使用过 Ruby,也会很熟悉 unless。它们在 E...

  • Elixir-文档模块

    Elixir提供了多种方式来编写注释或者是注解。下面是其中三种方式: # - 用于单行的注释 @moduledoc...

网友评论

      本文标题:Elixir-组合

      本文链接:https://www.haomeiwen.com/subject/wedqmftx.html