【问题标题】:Can a GenServer Have Its Own Struct in Elixir?GenServer 可以在 Elixir 中拥有自己的结构吗?
【发布时间】:2019-01-29 14:09:51
【问题描述】:

场景:

  • 我有一个简单的 GenServer 用于管理某些状态。
  • 目前,我使用 map 来管理我的状态。但它正在增长 我正在向该州添加更多数据。

问题:

  • 那么,为了获得一些编译时保证,我可以在我的GenServer 模块中添加一个struct 吗?
  • 如果是,这是一种正确的方法吗?
  • 如果没有,有哪些替代方案?

【问题讨论】:

    标签: elixir gen-server


    【解决方案1】:

    只需声明一个普通结构(可选地在嵌套在GenServer 命名空间中的模块中)并将其用作初始状态:

    defmodule Test do
      defmodule State do
        defstruct ~w|foo bar baz|a
      end
    
      use GenServer
    
      def start_link(opts \\ []) do
        GenServer.start_link(__MODULE__, %State{foo: 42, bar: opts}, name: __MODULE__)
      end
    
      @impl true
      def init(opts \\ []), do: {:ok, opts}
    
      def state, do: GenServer.call(__MODULE__, :state)
    
      @impl true
      def handle_call(:state, _from, %State{} = state) do
        {:reply, state, state}
      end
    end
    
    with {:ok, _} <- Test.start_link(pi: 3.14) do
      IO.inspect Test.state, label: "State"
    end
    #⇒ State: %Test.State{bar: [pi: 3.14], baz: nil, foo: 42}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 2019-11-19
      • 2015-06-15
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      相关资源
      最近更新 更多