Elixir跳过运算符而不是另一条消息?

时间:2018-02-03 16:49:30

标签: elixir

我想知道如何在3_000毫秒之后跳到此功能的结尾,但屏幕上没有任何其他打印消息或调用其他功能或发送更多消息。

defmodule ExampleModule do

    def main do
        Process.send_after(self(), :hello, 2_000)
        send self(), :hello_again
        next()
    end

    def next do
        receive do
            :hello -> IO.puts("Received hello") 
            :hello_again -> IO.puts("Received hello_again")
            after 3_000 -> <SKIP to the very end without recursion>
       end 
        next()
    end
end

1 个答案:

答案 0 :(得分:2)

Elixir中没有gotoreturn等构造。您可以通过以下两种方式解决此问题:

  1. 在要继续递归的分支中明确调用next()

    def next do
      receive do
        :hello ->
          IO.puts("Received hello") 
          next()
        :hello_again ->
          IO.puts("Received hello_again")
          next()
        after 3_000 ->
          :ok
      end 
    end
    
  2. 存储接收表达式的值并根据以下内容调用next()

    def next do
      continue = receive do
        :hello ->
          IO.puts("Received hello") 
          true
        :hello_again ->
          IO.puts("Received hello_again")
          true
        after 3_000 ->
          false
      end 
      if continue, do: next()
    end