简体   繁体   English

有什么意义:Elixir的GenServer示例中的ok init参数?

[英]What's the point of the :ok init argument in Elixir's GenServer example?

In Elixir's intro to GenServer , the client API starts the server with an :ok argument Elixir的GenServer简介中 ,客户端API使用:ok参数启动服务器

def start_link(opts \\ []) do
  GenServer.start_link(__MODULE__, :ok, opts)
end

And the server's init function requires its argument to be :ok 服务器的init函数要求其参数为:ok

def init(:ok) do
  {:ok, HashDict.new}
end

What's the point of passing and verifying :ok ? 通过和验证有什么意义:ok Would it be any different if we were to omit this and instead write something like 如果我们省略这个而不是写一些类似的东西会有什么不同吗?

def start_link(opts \\ []) do
  GenServer.start_link(__MODULE__, nil, opts)
end

def init(_) do
  {:ok, HashDict.new}
end

?

Its important to remember here that the second argument passed to start_link will become the argument of the init function. 重要的是要记住传递给start_link的第二个参数将成为init函数的参数。 Because this is a simple example they have used atom like :ok and can be replaced by nil. 因为这是一个简单的例子,他们使用了原子,如:ok,可以用nil代替。 You need to pass the second argument be it nil. 你需要传递第二个参数,无论如何。

So answering your question, in this example :ok can be replaced by nil . 所以回答你的问题,在这个例子中:ok可以用nil代替。 I think they used :ok since there must be an argument and :ok looks like a good choice(just a preference) 我认为他们使用了:ok因为必须有一个参数而且:ok看起来是个不错的选择(只是一个偏好)

In other situations you have to make use of this information to fetch some important data or for pattern matching 在其他情况下,您必须使用此信息来获取一些重要数据或用于模式匹配

defmodule ServerDrop do
   use GenServer

defmodule State do
    defstruct count: 0
end

def start_link do
    GenServer.start_link(__MODULE__,:ok,[{:name,__MODULE__}])
    #GenServer.start_link(__MODULE__,[],[{:name,__MODULE__}])
end

def init(:ok) do
    {:ok,%State{count: 10}}
end

def init([]) do
    {:ok,%State{}}
end

#Code left out for brevity

In other situations you many need to get some data 在其他情况下,您需要获取一些数据

def init(stash_pid) do
    current_number = Stash.get_value stash_pid
    {:ok,{current_number,stash_pid}}
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM