英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论