3.4 Booleans

A value of type bool, or boolean, has only two possible values, true and false. The conditions in if and for statements are booleans, and comparison operators like == and < produce a boolean result. The unary operator ! is logical negation, so !true is false, or, one might say, (!true==false)==true, although as a matter of style, we always simplify redundant boolean expressions like x==true to x.

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
}

It might be worth writing a conversion function if this operation were needed often:

// btoi returns 1 if b is true and 0 if false.
func btoi(b bool) int {
    if b {
        return 1
    }
    return 0
}

The inverse operation is so simple that it doesn’t warrant a function, but for symmetry here it is:

// itob reports whether i is non-zero.
func itob(i int) bool { return i != 0 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.12.101