I want to run a function multiple times and then do something if anything failed.
So I set a flag before looping the calls, the called function comes back with a success/failure boolean but, if I use an in-line logical AND, the function is no longer called as though an IF statement exists. Can someone explain this?
Example in GO Playground (https://go.dev/play/p/I5DP2mDmoqI)
package main
import "fmt"
func main() {
fmt.Println("In-line logical AND")
resultOK := true
for i := 0; i < 10; i {
resultOK = resultOK && doSomething(i)
}
fmt.Println("Separate line for logical AND")
resultOK = true
for i := 0; i < 10; i {
result := doSomething(i)
resultOK = resultOK && result
}
}
func doSomething(i int) bool {
fmt.Println("Hello, 世界", i)
return i%2 == 0
}
Resulting output
In-line logical AND
Hello, 世界0 : true
Hello, 世界1 : false
: false
: false
: false
: false
: false
: false
: false
: false
Separate line for logical AND
Hello, 世界0 : true
Hello, 世界1 : false
Hello, 世界2 : false
Hello, 世界3 : false
Hello, 世界4 : false
Hello, 世界5 : false
Hello, 世界6 : false
Hello, 世界7 : false
Hello, 世界8 : false
Hello, 世界9 : false
CodePudding user response:
The difference is short-circuit evaluation.
If the left operand of the logical AND is false
, the result will be false
, so the right operand is not evaluated. In your first example the right operand is the function call, so the function will NOT be called. Similarly, if the first operand of a logical OR is true
, the result is true
, so the right operand in that case would not be evaluated either.
This is mentioned in Spec: Logical operators:
Logical operators apply to boolean values and yield a result of the same type as the operands. The right operand is evaluated conditionally.
In the second example the function is called before the logical AND, so it is called no matter what resultOK
is.