在Go的規格書裡面有寫到以下敘述
&& conditional AND p && q is "if p then q else false"
|| conditional OR p || q is "if p then true else q"
! NOT !p is "not p"
這是一種叫做Short-circuit evaluation的優化方法
以p && q
來說,如果p是false的話其實就保證這個結果一定是false,這時候就不用特別再去看q了。反過來說p || q
也是一樣的,如果p是true,q是什麼值都不會影響最終結果。
package main
import "fmt"
func TrueHere() bool {
fmt.Println("call TrueHere")
return true
}
func FalseHere() bool {
fmt.Println("call FalseHere")
return false
}
func main() {
fmt.Println("&&")
if FalseHere() && TrueHere() {}
/*
output:
&&
call FalseHere
*/
fmt.Println("||")
if TrueHere() || FalseHere() {}
/*
output:
||
call TrueHere
*/
}