Execution Order of Logical Operators
When using logical AND and logical OR operators, Go needs to determine the boolean values on both sides of the operator. But which side is evaluated first?
Let's explore this together.
Write the following code in opePractice.go
:
package main
import "fmt"
func leftFunc(flag bool) bool {
fmt.Println("Left function is called!")
return flag
}
func rightFunc(flag bool) bool {
fmt.Println("Right function is called!")
return true
}
func main() {
if leftFunc(true) && rightFunc(true) {
fmt.Println("Evaluation is complete")
}
}
Run the code:
Left function is called!
Right function is called!
Evaluation is complete
It is not difficult to find out that in the logical AND operation, the left condition is evaluated first, and then the right condition is evaluated.
What about the logical OR operation? Write the following code in opePractice.go
:
package main
import "fmt"
func leftFunc(flag bool) bool {
fmt.Println("Left function is called!")
return flag
}
func rightFunc(flag bool) bool {
fmt.Println("Right function is called!")
return true
}
func main() {
if leftFunc(true) || rightFunc(true) {
fmt.Println("Logical OR evaluation is complete")
}
}
Run the code:
Left function is called!
Logical OR evaluation is complete
The evaluation order of both logical AND and logical OR operations is from left to right.
However, in the logical OR operation, if the left condition is true, the right condition is not evaluated.
Therefore, in actual development, we should place the conditions that are more likely to be evaluated to the left of the logical OR operator, reducing the execution time of the program.