Skip to main content

How to Combine Conditions with AND (&&), OR (||) and NOT (!) in Go

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

Go combines true-or-false conditions with three logical operators: a && b is true when both sides are true, a || b when at least one is, and !a turns true into false and false into true. && and || skip their right side when the left side already decides the answer, which lets a check such as len(roles) > 0 protect the code after it.

Syntax​

Syntax
<a> && <b>
<a> || <b>
!<a>
PartWhat it does
<a> && <b>AND: true only when both <a> and <b> are true. If <a> is false, <b> isn't evaluated.
<a> || <b>OR: true when <a>, <b> or both are true. If <a> is true, <b> isn't evaluated.
!<a>NOT: true when <a> is false, and false when it's true.
<a>, <b>Expressions of type bool, such as age >= 65 or a bool variable.

The Go specification, Logical operators: "Logical operators apply to boolean values and yield a result of the same type as the operands. The left operand is evaluated, and then the right if the condition requires it."

The Example​

The example checks a user who is signed in, isn't banned and is 70. It prints one &&, one || and one !, then uses && to check that a slice of roles isn't empty before it reads the first role. A changed version of the program then reads the first role without that check.

Prerequisites​

  • Go. go run compiles and runs a single file. This guide uses Go 1.27.4.

Step 1: Write the Code​

Create a file named main.go:

main.go, which sets signedIn to true, banned to false and age to 70, prints signedIn AND NOT banned, age under 12 OR at least 65, and NOT signedIn, then checks that an empty roles slice has at least one element before it compares the first one with admin.

main.go
package main

import "fmt"

func main() {
signedIn := true
banned := false
age := 70

// && is true only when both sides are true.
fmt.Println("can comment:", signedIn && !banned)
// || is true when at least one side is true.
fmt.Println("pays the reduced price:", age < 12 || age >= 65)
// ! turns true into false, and false into true.
fmt.Println("must sign in:", !signedIn)

var roles []string // no roles yet: an empty slice
// && skips its right side when the left side is false, so roles[0] is never read.
fmt.Println("first role is admin:", len(roles) > 0 && roles[0] == "admin")
}

var roles []string declares a slice with no elements, the way a user with no roles would arrive.

Step 2: Run It​

Terminal
go run main.go
Output
can comment: true
pays the reduced price: true
must sign in: false
first role is admin: false

The command is the same in zsh, bash and PowerShell.

Step 3: Read the First Role Without the Check​

Replace main.go with a version that compares the first role without checking the slice's length first:

main.go
package main

import "fmt"

func main() {
var roles []string // no roles yet: an empty slice
// Without the length check, roles[0] is read from an empty slice.
fmt.Println("first role is admin:", roles[0] == "admin")
}
Terminal
go run main.go
Output
panic: runtime error: index out of range [0] with length 0

goroutine 1 [running]:
main.main()
/Users/Shared/you/main.go:8 +0x1c
exit status 2

A zsh terminal where go run main.go prints can comment: true, pays the reduced price: true, must sign in: false and first role is admin: false, then, for the changed file, stops with panic: runtime error: index out of range [0] with length 0 and exit status 2.

What Happened​

  • signedIn && !banned is true. !banned turned false into true, so both sides were true.
  • age < 12 || age >= 65 is true. The left side was false, but the right side was true for an age of 70.
  • !signedIn is false, because signedIn is true.
  • len(roles) > 0 && roles[0] == "admin" is false, with no error. The slice was empty, so the left side was false and && never evaluated roles[0].
  • Without the length check, the program stopped. roles[0] asked for the first element of an empty slice. The specification's Index expressions say that for a slice, "if x is out of range at run time, a run-time panic occurs". The panic names the index and the length, main.go:8 is the line that read roles[0], and go run then printed exit status 2.

Common Mistakes​

MistakeWhat happensDo this instead
Using a number with &&, as in age && signedIninvalid operation: age && signedIn (mismatched types int and bool), because Go never treats a number as true or falseCompare the number first, as in age >= 65
Writing !age >= 65 to mean "not 65 or over"invalid operation: operator ! not defined on age (variable of type int), because ! applies to age firstAdd parentheses: !(age >= 65)
Using & or | between two bool valuesinvalid operation: operator & not defined on signedIn (variable of type bool). In Go, & and | work only on integersUse && and ||
Putting the index before the length check, as in roles[0] == "admin" && len(roles) > 0The left side runs first, so the empty slice still panicsPut the check that protects the code on the left
Mixing && and || without parenthesesa || b && c means a || (b && c), which can differ from what you meantAdd parentheses to say which pair goes first

Troubleshooting​

SymptomLikely causeFix
invalid operation: ... (mismatched types int and bool)One side of && or || isn't a boolTurn it into a comparison
invalid operation: operator ! not defined on age (variable of type int)! stands before a number, or before a comparison without parenthesesPut the comparison in parentheses after !
panic: runtime error: index out of range [0] with length 0An element was read from an empty sliceCheck len(...) > 0 first and join the two with &&

FAQ​

Does Go have a & operator for bool values, like Java?​

No. In Go, & and | are bitwise operators for integers, so signedIn & !banned doesn't compile. && and || are the only AND and OR for bool values, and both always skip their right side when the left side decides the answer.

Which runs first, && or ||?​

&& binds tighter than ||. The specification's Operator precedence lists the comparison operators, then "&& (logical AND), and finally || (logical OR)". So a || b && c means a || (b && c): with a true and b and c false, a || b && c printed true, and (a || b) && c printed false.

Can I use a string or a pointer as a condition, as in JavaScript?​

No. A condition in Go must be a bool: if name { ... } with a string, or with a pointer, stops with non-boolean condition in if statement. Compare the value instead, as in name != "" or plan != nil.

Conclusion​

&& needs both sides to be true, || needs one, and ! flips a condition. Because && and || stop as soon as the answer is known, a check on the left, such as len(roles) > 0, keeps the code on the right from running when it would panic.

Additional Resources​