Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Operators

Go logical operators

Reference for Go's logical operators &&, || and !: boolean-only operands, short-circuit evaluation, precedence, guard idioms and De Morgan's laws.

Go has three logical operators: && (and), || (or) and ! (not). They work only on boolean values; there is no "truthiness", so if n with an integer or if !s with a string does not compile. Write the comparison you mean: n != 0, s == "".

&& and || short-circuit. The right operand is evaluated only if the left one does not already decide the result. This lets you guard a risky expression with a safe one.

Go
if p != nil && p.Active {
	// p.Active is only read when p is not nil
}

Try it

Go Short-circuit evaluation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Precedence and truth tables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
a && b    // true if both are true
a || b    // true if either is true
!a        // true if a is false
Operator Operands Evaluates right side when
&& two booleans the left side is true
|| two booleans the left side is false
! one boolean (unary)

The result has the same boolean type as the operands. With named boolean types both operands must have the same type.

Usage notes

  • Order of evaluation is left to right for && and ||, which is what makes guard conditions like i < len(s) && s[i] == 'x' safe.
  • Precedence from tightest to loosest: ! (unary), comparisons, &&, ||. Parenthesize mixed expressions for the reader even when not required.
  • No and/or/not words and no ^^ (xor). Use a != b for boolean exclusive-or.
  • Side effects. Do not put required calls on the right side of a && or ||: they might be skipped. The examples above show it deliberately.
  • No ternary operator. Use if/else; for a value, a small helper function or cmp.Or (Go 1.22) for the first non-zero value.
  • Don't compare booleans to constants. Write if ready, not if ready == true.
  • Early returns often replace nested logical conditions and read better than long chains.
  • Bitwise versus logical. & and | on booleans do not compile; they are for integers.