Booleans
Boolean values can be combined with the && (AND) and || (OR) operators, which have short-circuit behavior : if the answer is already determined by the value of the left operand, the right operand is not evaluated, making it safe to write expressions like this:
s != "" && s[0] == 'x' // where s[0] would panic if applied to an empty string .
Since && has higher precedence than || (mnemonic: && is boolean multiplication, || is boolean addition), no parentheses are required for conditions of this form:
if 'a' <= c && c <= 'z' ||
'A' <= c && c <= 'Z' ||
'0' <= c && c <= '9' {
// ...ASCII letter or digit...
}
There is no implicit conversion from a boolean value to a numeric value like 0 or 1, or vice versa. It’s necessary to use an explicit if , as in:
i := 0
if b {
i = 1
}
// conversion function. // btoi returns 1 if b is true and 0 if false.
func btoi(b bool) int {
if b {
return 1
}
return 0
}
// itob reports whether i is non-zero.
func itob(i int) bool { return i != 0 }