我正在尝试实现这个非常简单的计数器,每当我调用我的方法时,它应该递增并打印它。但由于某种原因,它增加了计数器,但没有打印出来。
defmodule Node2 do
def start() do
initial = 0
loop(initial)
end
def loop(counter) do
receive do
{:rumor, msg, from} ->
IO.puts "#{msg} received from :"
IO.inspect from
counter = counter + 1
IO.puts "Value of a Counter:"
IO.puts counter
loop(counter)
{:get_counter, msg, from} ->
IO.puts "Counter Value"
end
end
def send_rumor(to_pid, from_pid, msg) do
IO.puts "Send_rumor function!"
send(to_pid, {:rumor, msg, from_pid})
end
end
我调用它的客户端方法定义如下:
pid = spawn(fn -> Node2.start() end)
Node2.send_rumor(pid, self(), "Hello Sir!")
输出如下:
Send_rumor function!
Hello Sir! received from :
#PID<0.77.0>
Value of a Counter:
它没有显示计数器的值并打印空白。 但奇怪的是,当我对代码进行这一小改动时,我只是在start函数中打印变量initial,它正确地给出了输出。
def start() do
initial = 0
IO.puts initial
loop(initial)
end
新输出:
Send_rumor function!
0
Hello Sir! received from :
#PID<0.77.0>
Value of a Counter:
1
我是Elixir的新手,所以不确定这里发生了什么?