【问题标题】:Does Elixir allow defstruct to call a function defined in the same module?Elixir 是否允许 defstruct 调用在同一模块中定义的函数?
【发布时间】:2018-03-16 03:49:15
【问题描述】:

我有一个看起来像这样的模块:

defmodule Othello.Game do
  alias Othello.Game, as: Game
  alias Othello.Utils, as: Utils

  defstruct enabled_spaces: Utils.gen_list(Game.width() * Game.width(), fn _ -> false end),
            is_game_over: false,
            is_first_player: true

  def width(), do: 8
end

是否可以从 defstruct 调用 width() 函数?

【问题讨论】:

  • 旁注:alias 的调用可能会缩短为alias Othello.{Game,Utils}

标签: elixir


【解决方案1】:

这是不可能的,因为定义 structmodule 仍需要编译才能使其功能正常工作,如下例所示:

iex(1)> defmodule A do
...(1)> def a, do: 1
...(1)> defstruct a: __MODULE__.a()
...(1)> end
** (UndefinedFunctionError) function A.a/0 is undefined (function a/0 is not available)
    A.a()
    iex:3: (module)

替代:定义一个模块属性并使用它来代替:

defmodule Othello.Game do
  @width 8
  alias Othello.Game, as: Game
  alias Othello.Utils, as: Utils

  defstruct enabled_spaces: Utils.gen_list(@width * @width, fn _ -> false end),
            is_game_over: false,
            is_first_player: true

  def width(), do: @width
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 2018-09-14
    • 2016-12-04
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多