Elixir:在if语句中设置变量 [英] Elixir: Set variable in if statement

查看:99
本文介绍了Elixir:在if语句中设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Elixir很陌生,这个简单的问题使我发疯。

I'm very new to Elixir and this simple problem is driving me nuts.

a = 0
if true do
    a = 1 + 1
end 
a = a + 1

IO.puts (a)

有趣的是,它给出了正确的值,但同时也给出了警告:

Interestingly this gives the correct value but also gives a warning:

warning: the variable "a" is unsafe as it has been set inside a case/cond/receive/if/&&/||. Please explicitly return the variable value instead. For example:

case int do
  1 -> atom = :one
  2 -> atom = :two
end

should be written as

atom =
  case int do
    1 -> :one
    2 -> :two
  end

Unsafe variable found at:
  Untitled:5

3

我不理解警告消息。在Elixir中执行此操作的最佳方法是什么?

I don't understand the warning message. What is the best way of doing this in Elixir?

更新:这种情况也如何?

Update: What about this condition too?

a = 0
b = 0
if true do
    a = 1 + 1
    b = 2 + 2
end 
a = a + 1
b = b + 2

IO.puts (a)
IO.puts (b)


推荐答案

在Elixir中,每个语句都返回该值。代替在 if 中分配变量,您可以将整个 if 语句值分配给变量。

In Elixir every statement returns the value. Instead of assigning variable in if you can assign whole if statement value into variable.

a = 0
a = if true do
      1 + 1
    else
      a + 1
    end

这篇关于Elixir:在if语句中设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆