Does Go Implement Short Circuit Evaluation?
Short circuit evaluation refers to the practice of only evaluating an expression in an if statement if it is necessary to determine the result of the statement. In other words, if the first expression in an if statement evaluates to false, the remaining expressions are not evaluated.
Go does implement short circuit evaluation. This can be illustrated with the following code:
package main import "fmt" func main() { for i := 0; i < 10; i++ { if testFunc(1) || testFunc(2) { // do nothing } } } func testFunc(i int) bool { fmt.Printf("function %d called\n", i) return true }
When this code is executed, it will print the following output:
$ function 1 called $ function 1 called $ function 1 called $ function 1 called $ function 1 called $ function 1 called $ function 1 called $ function 1 called $ function 1 called $ function 1 called
As you can see, the function testFunc(2) is never called, because the first expression in the if statement (testFunc(1)) evaluates to true. This demonstrates that Go implements short circuit evaluation.
The above is the detailed content of Does Go Utilize Short Circuit Evaluation in Boolean Expressions?. For more information, please follow other related articles on the PHP Chinese website!