if语句中的所有条件是否都会被执行?

huangapple go评论90阅读模式
英文:

does go excecute all conditions in if statement?

问题

在这种情况下,如果function1(input)返回false,function2(input)会被执行吗?

英文:

Example:

if function1(input) && function2(input) {}

In this case would function2(input) be executed if function1(input) returns false?

答案1

得分: 15

你所询问的被称为“短路评估”,Go语言确实支持这个特性。

在语言规范中,它指出:

逻辑运算符应用于布尔值,并产生与操作数相同类型的结果。右操作数在条件下进行评估。

这意味着,在你的情况下,如果function1返回false,function2将不会被调用。

在这里可以看到&&的示例,以及||的示例

英文:

What you are asking about is called Short Circuiting, and yes, Go does it.

In the language spec, it says that

> Logical operators apply to boolean values and yield a result of the same type as the operands. The right operand is evaluated conditionally.

This means that, in your case, if function1 returned false, function2 would not be called.

See an example for && here and for || here.

答案2

得分: 4

Go语言使用标准的条件快捷逻辑——在一系列&&条件中,第一个false结果将停止对后续条件的评估(因为无论其他条件如何,它都无法产生true结果)。同样地,在一系列||条件中,第一个true结果将停止评估,因为无论其他条件如何,它都无法产生false结果。

英文:

No. Go uses standard conditional shortcut logic - the first false result in a string of && conditions will stop evaluation of further conditions (because it cannot yield a true result no matter what the other conditions are). Likewise, the first true result in a string of || conditions will stop evaluation because it cannot yield a false result no matter what the other conditions are.

huangapple
  • 本文由 发表于 2017年8月16日 01:33:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/45698298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定