gpt4 book ai didi

elixir - Elixir 中 GenServer 可以有自己的结构吗?

转载 作者:行者123 更新时间:2023-12-02 18:17:25 26 4
gpt4 key购买 nike

场景:

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

问题:

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

最佳答案

只需声明一个普通结构(可以选择在 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}

关于elixir - Elixir 中 GenServer 可以有自己的结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51981683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com