The Analogy: The Lab Bench and the Sample Tray
A technician takes a sample, puts it on a small tray on the bench, runs the test, reads the result, and clears the tray before the next patient. The tray is part of the test, not part of the laboratory. Nothing from the previous sample is still sitting there when the next one arrives, and nobody down the corridor can reach over and use it. The scope of that tray is exactly one decision, and that is what makes the process safe: there is no way for yesterday's sample to contaminate today's result, because yesterday's sample no longer exists anywhere.
The results themselves are also deliberately narrow. A test reports positive or negative. It does not report "three milliliters" and leave the reader to decide whether three counts as positive. If the raw measurement matters, the protocol states the threshold, in writing, and the threshold is part of the test rather than part of the reader's judgment. A laboratory that let each doctor decide what counted as a positive would produce numbers nobody could compare.
A good bench also rejects bad samples immediately. Wrong tube, no label, drawn too long ago: those go back at the door, one check at a time, and each rejection ends the process for that sample. What survives to the end of the checklist is known to be good. Nobody writes a nested flowchart where a mislabeled tube travels through six more steps before somebody notices.
Go's if statement is built around all three habits. It can declare variables that live only for the duration of the decision, like the tray. It requires an actual boolean, never a number that might be interpreted as one. And the idiom the whole language pushes you toward is a flat sequence of rejections followed by the happy path, rather than a pyramid of nesting. This lesson is about all three, plus the surprising question of which Go values can be compared at all.
Syntax or Core Structure
There are no parentheses around the condition and the braces are never optional. The interesting part is the optional initializer before the semicolon.
package main
import (
"fmt"
"strconv"
)
// withElse uses the initializer form and an if/else chain.
func withElse(raw string) string {
if n, err := strconv.Atoi(raw); err != nil {
return "invalid"
} else if n < 0 {
return "negative"
} else {
return "ok:" + strconv.Itoa(n*2)
}
}
// guarded says exactly the same thing with early returns and no else.
func guarded(raw string) string {
n, err := strconv.Atoi(raw)
if err != nil {
return "invalid"
}
if n < 0 {
return "negative"
}
return "ok:" + strconv.Itoa(n*2)
}
func main() {
for _, raw := range []string{"21", "-3", "abc"} {
fmt.Printf("%-4s withElse=%-9s guarded=%s\n", raw, withElse(raw), guarded(raw))
}
if n := len("go"); n > 0 {
fmt.Println("len is", n, "which is greater than zero")
}
// fmt.Println(n) // error: n does not exist out here
// if len("go") { } // error: non-boolean condition
}
Output:
21 withElse=ok:42 guarded=ok:42
-3 withElse=negative guarded=negative
abc withElse=invalid guarded=invalid
len is 2 which is greater than zero
Both functions produce identical answers, and the second one is the one to write. guarded has no else at all, every failing case leaves the function on the line where it is detected, and the successful path is the last line at the leftmost indentation. withElse needs the reader to hold three branches open at once to work out which one returns what.
Technical Depth: Conditions, Scope and Comparability
A Condition Must Be a bool
Go has no truthiness. There is no rule converting a number, a string, a slice or a pointer into a boolean, so the compiler rejects the shorthand you may be used to.
| Other languages | Go requires |
|---|---|
if count | if count != 0 |
if name | if name != "" |
if items | if len(items) > 0 |
if ptr | if ptr != nil |
if !err | if err == nil |
The gain is that the threshold is written down. if items is ambiguous about whether an empty list counts, and if len(items) > 0 is not. It costs a few characters and removes a class of review question.
The Initializer and Its Scope
if v, ok := cache[key]; ok {
return v // v is in scope here
} else {
log(key, v) // and here, in the else branch too
}
// neither v nor ok exists on this line
Variables declared in the initializer are scoped to the whole if/else if/else chain and nowhere else. That is the sample tray: it exists for one decision. The same form appears in switch and for, and the three most common uses are worth memorizing.
| Form | Meaning |
|---|---|
if v, ok := m[k]; ok | Map lookup that distinguishes missing from zero |
if v, ok := x.(T); ok | Type assertion that does not panic |
if err := do(); err != nil | Call something for its error alone |
That third form is the one to reach for whenever you do not need the result, because it keeps err out of the enclosing function entirely and removes any chance of testing a stale one later.
Write for the Line of Sight
The Go community's name for the guard clause habit is keeping the line of sight: the happy path runs down the left edge of the function, and every indentation is an exception.
// Nested: the reader must track three open conditions.
func handle(r *Request) error {
if r != nil {
if r.User != nil {
if r.User.Active {
return process(r)
} else {
return errInactive
}
}
return errNoUser
}
return errNilRequest
}
// Flat: each failure is dismissed and forgotten.
func handle(r *Request) error {
if r == nil {
return errNilRequest
}
if r.User == nil {
return errNoUser
}
if !r.User.Active {
return errInactive
}
return process(r)
}
The second version has the same branches and less to hold in your head. It also survives editing better: adding a fourth check means adding three lines at the top, not re-indenting the body.
Which Values Can Be Compared At All
== is not universally available in Go, and the rules are worth learning once rather than discovering through compile errors.
| Type | == and != | < and > |
|---|---|---|
| Numbers | Yes | Yes |
string | Yes | Yes, byte by byte |
bool | Yes | No |
| Pointer, channel | Yes, identity | No |
| Struct | Yes, if every field is comparable | No |
| Array | Yes, if the element type is comparable | No |
| Interface | Yes, type and value both | No |
| Slice, map, function | Only against nil | No |
Two consequences catch people out. A struct containing a slice cannot be compared with == at all, which turns into a compile error the moment somebody adds a slice field to a previously comparable struct. And comparing two interface values whose dynamic type is not comparable, such as two any values both holding slices, compiles fine and panics at run time with comparing uncomparable type.
For the types == refuses, use the standard library rather than writing loops: slices.Equal, maps.Equal, bytes.Equal, or reflect.DeepEqual when you need a general answer and can afford reflection. Floating point has its own trap: math.NaN() == math.NaN() is false, so a NaN in a struct makes that struct unequal to itself.
Ordering strings compares raw bytes, which means uppercase sorts before lowercase and it is not a human alphabetical order. Use strings.ToLower before comparing, or golang.org/x/text/collate when the answer has to be correct for a particular language.
Short Circuit Evaluation Is a Tool, Not Trivia
&& and || stop as soon as the answer is known, and Go guarantees it, so the left operand can be a guard for the right one.
if user != nil && user.Active { // safe: never dereferences nil
if cached, ok := m[k]; ok && cached.Fresh {
if err == nil || errors.Is(err, io.EOF) {
Reversing the first condition is a nil pointer dereference, which is one of the few Go panics you can write by accident in a single line.
There Is No Ternary Operator
Go deliberately has no cond ? a : b. The replacement is an if statement, and for the common cases the standard library now covers them:
limit := 10
if requested > 0 {
limit = requested
}
limit = min(requested, 100) // builtin since Go 1.21
name := cmp.Or(input, "anonymous") // first non-zero value
Four lines instead of one, and no nested conditional expressions in an argument list. This is the same trade the whole language makes: slightly more typing, considerably less to decode.
Real World Example: A Validator That Reads Like a Checklist
Signup validation is the purest form of this pattern. There is a list of conditions, any one of them can reject the request, and the code should be readable by the person who wrote the product requirements.
package main
import (
"fmt"
"strings"
)
type Signup struct {
Email string
Password string
Age int
Country string
Accepted bool
}
// A map used as a set: a missing key reads as false, which is exactly
// the answer we want for an unsupported country.
var supported = map[string]bool{"gb": true, "de": true, "fr": true}
// validate returns the first problem it finds, or "" when everything passed.
func validate(s Signup) string {
if s.Email == "" {
return "email is required"
}
if !strings.Contains(s.Email, "@") {
return "email must contain @"
}
if n := len(s.Password); n < 10 {
return fmt.Sprintf("password is %d characters, need 10", n)
}
if s.Age < 18 {
return "must be 18 or older"
}
if country := strings.ToLower(s.Country); !supported[country] {
return "country not supported: " + country
}
if !s.Accepted {
return "terms must be accepted"
}
return ""
}
func main() {
good := Signup{
Email: "ada@example.com",
Password: "correct-horse",
Age: 36,
Country: "GB",
Accepted: true,
}
cases := []Signup{good, good, good, good, good, good}
cases[1].Email = ""
cases[2].Email = "ada.example.com"
cases[3].Password = "short"
cases[4].Age = 17
cases[5].Country = "US"
for i, c := range cases {
if problem := validate(c); problem != "" {
fmt.Printf("case %d: rejected - %s\n", i+1, problem)
continue
}
fmt.Printf("case %d: accepted\n", i+1)
}
}
Output:
case 1: accepted
case 2: rejected - email is required
case 3: rejected - email must contain @
case 4: rejected - password is 5 characters, need 10
case 5: rejected - must be 18 or older
case 6: rejected - country not supported: us
Read validate top to bottom and it is the requirements document. Every line at the leftmost indentation is a rejection, each one names its own reason, and there is exactly one way to reach the end: pass all six checks. There is no else in the function, nothing is nested more than one level, and adding a seventh rule means inserting four lines rather than re-indenting anything. This is what the line of sight habit buys, and it scales: a validator with twenty rules written this way is still readable, while the nested version stops being reviewable at about four.
Two of the checks use the initializer form, and they do it for different reasons. if n := len(s.Password); n < 10 needs the length twice, once in the comparison and once in the message, and the initializer means n cannot leak into the rest of the function or be confused with some other length later. if country := strings.ToLower(s.Country); !supported[country] needs the normalized value for both the lookup and the error text. In main, if problem := validate(c); problem != "" does the same job: the result is examined once and then it is gone.
The supported map is doing something specific that only works because of Go's zero values. Looking up a key that is not there returns the zero value of the map's value type, which for bool is false, so !supported["us"] is true without any existence check at all. That is why map[string]bool is the idiomatic Go set, and why you only need the two value form v, ok := m[k] when zero and missing must be told apart. Here they mean the same thing, so one value is enough.
The way the test cases are built is a value semantics lesson hiding in plain sight. []Signup{good, good, good, ...} copies the struct six times, so assigning to cases[1].Email cannot affect good or any other element. That is only safe because every field of Signup is a value type; had it contained a slice or a map, all six copies would share the same backing data and the fifth test would quietly corrupt the second. Two other decisions in this function are worth naming as decisions rather than accidents: it returns the first problem instead of collecting all of them, which is a product choice about how forms report errors, and it returns a string where real Go would return an error. Module 7 replaces the string.
Common Mistakes
- Writing
if countorif name. There is no truthiness in Go. Saycount != 0orname != ""and the threshold becomes part of the code instead of part of the reader's assumptions.
- Nesting the happy path. If your successful return is four levels deep, invert every condition and return early. The rewrite is mechanical and always improves the function.
- Using an
elseafter a branch that returns.if err != nil { return err } else { ... }never needs theelse. Drop it and un-indent the body.
- Declaring the initializer variable outside when it is only needed inside.
err := do(); if err != nil {}leaves a staleerrin scope for the rest of the function.if err := do(); err != nil {}does not.
- Comparing structs that contain slices.
==will not compile, and if the values are hidden inside ananyit compiles and panics at run time instead. Useslices.Equalorreflect.DeepEqual.
- Checking a pointer's field before the pointer.
if u.Active && u != nilpanics. Short circuit evaluation only helps when the guard comes first.
- Assuming string ordering matches the alphabet.
"Zebra" < "apple"is true because comparison is by byte value. Normalize the case first, or use a collation package when human ordering matters.
- Comparing floats for equality. Use a tolerance, and remember that
NaNis not equal to itself, which also makes any struct containing one unequal to itself.
- Simulating a ternary with a helper for everything. A three line
ifis clearer thanternary(cond, a, b), andmin,maxandcmp.Oralready cover the cases worth naming.
Best Practices
- Reject invalid input at the top of the function with one guard clause per rule, and let the happy path be the last statement.
- Use the initializer form whenever a value is needed only for the decision, especially for map lookups, type assertions and error-only calls.
- Compare against an explicit threshold rather than relying on a value being non-zero implicitly.
- Put the nil check on the left of
&&and rely on short circuit evaluation instead of nesting. - Use
map[string]boolas a set and let the missing key read as false; reach forv, okonly when zero and absent differ. - Prefer
slices.Equalandmaps.Equalover hand written comparison loops, and know that==on a struct is a field by field comparison. - Keep each condition small enough to read aloud; when it needs a comment, give it a named boolean or a small function instead.
- Let the error case be the indented one and the successful case be the plain one, in every function you write.
Practice Exercises
- Flatten a Pyramid: Write a function four levels deep that checks a request, a user, a subscription and a quota before doing work. Then rewrite it with guard clauses only. Count the lines and the maximum indentation of both versions, and note which one you would rather add a fifth check to.
- Prove the Scope: Write
if v, ok := m["missing"]; ok { ... }and then try to printvon the following line. Record the compile error. Then move the declaration outside theifand explain what new mistake becomes possible.
- Find the Comparability Wall: Define a struct with two
stringfields and compare two values with==. Add a[]stringfield and observe what breaks. Then store both values inanyvariables, compare those, and record the run time panic message.
- Checklist Validator: Write a validator for a payment request with at least six rules, using one guard clause each, an initializer where a value is needed twice, and a
map[string]boolfor a set of allowed currencies. Then change it to collect every problem into a[]stringinstead of returning the first, and write one sentence on when each version is the right product behavior.