Menu

Golang if else: Syntax, Init Statements and if err != nil

How if, else if and else work in Go: no parentheses, required braces, the if statement with an init clause and its scope, the if err != nil idiom, and early returns instead of deep nesting.

This page includes runnable editors - edit, run, and see output instantly.

Go's if has no parentheses around the condition, always requires braces, and can start with a short statement that declares variables scoped to the if.

Conditions are checked from the top and the first true branch runs. else if and else are optional.

Syntax Rules

Three rules differ from C, Java and JavaScript:

  1. No parentheses around the condition. if (x > 5) compiles, but gofmt removes the parentheses.
  2. Braces are required, even for one statement. There is no braceless if x > 5 return.
  3. else goes on the same line as the closing brace. Go inserts a semicolon after a } at the end of a line, so this fails:
if x > 5 {
	fmt.Println("big")
}
else {
	fmt.Println("small")
}
syntax error: unexpected keyword else, expected }

Write } else { on one line.

The condition must be a bool. Go does not treat 0, "" or nil as false, so if count {} and if name {} do not compile. Compare explicitly: if count > 0, if name != "", if user != nil.

Combine conditions with && (and), || (or) and ! (not). Both && and || short-circuit, which makes nil checks safe:

if user != nil && user.IsAdmin() {
	// user.IsAdmin() is only called when user is not nil
}

if with an Init Statement

An if can run one short statement before the condition, separated by a semicolon. Variables declared in it are visible in every branch of that if, and nowhere after:

The pattern keeps short-lived variables out of the surrounding scope. It appears constantly with map lookups (v, ok := m[k]), type assertions (s, ok := v.(string)) and errors.

The flip side: if you need the value after the if, declare it before instead. A common mistake is putting a result in the init statement and then trying to use it below.

The if err != nil Idiom

Functions that can fail return an error last. Check it immediately, handle or return it, and continue with the happy path unindented:

Notice there is no else after if err != nil { return ... }. Go style handles the error, returns, and leaves the normal flow at the left margin. The error handling page covers wrapping and checking error types.

Early Returns Instead of Nesting

Deeply nested if blocks are hard to read. Invert the conditions and return early; each check then reads as a guard:

// Nested
func canCheckout(u *User, cart *Cart) bool {
	if u != nil {
		if u.Verified {
			if len(cart.Items) > 0 {
				return true
			}
		}
	}
	return false
}

// Guards
func canCheckout(u *User, cart *Cart) bool {
	if u == nil || !u.Verified {
		return false
	}
	if len(cart.Items) == 0 {
		return false
	}
	return true
}

Go programmers call this keeping the happy path left-aligned. Linters such as revive flag an else after a block that ends in return, because the else adds indentation for nothing.

if/else vs switch

A long chain of else if that tests one value against several cases reads better as a switch. A switch with no expression replaces an if/else if chain of arbitrary conditions:

switch {
case score >= 90:
	return "A"
case score >= 80:
	return "B"
default:
	return "F"
}

Use if for one or two branches, and switch once there are three or more.

No Ternary Operator

Go has no cond ? a : b. Assign with if:

label := "odd"
if n%2 == 0 {
	label = "even"
}

The ternary operator page explains why and shows the alternatives.

Common Mistakes

  • Shadowing with :=. if x, err := f(); err == nil { ... } declares a new x for the if only. An outer x is not updated.
  • Assignment in the condition. if x = 5 {} is a compile error (cannot use assignment x = 5 as value), not a silent bug as in C. Use ==.
  • Comparing floats with ==. if total == 0.3 fails for computed values. Compare with a tolerance.
  • Checking the wrong error. After a, err := f() and b, err := g(), make sure each if err != nil sits right after its call.

Frequently Asked Questions

How do you write if else in Go?

Without parentheses around the condition, and with braces always required:

if x > 10 {
	fmt.Println("big")
} else if x > 5 {
	fmt.Println("medium")
} else {
	fmt.Println("small")
}

else must be on the same line as the closing brace of the previous block.

What is an if statement with an init statement in Go?

A short statement before the condition, separated by a semicolon: if n, err := strconv.Atoi(s); err != nil { ... }. Variables declared there exist only inside the if and its else if and else branches, which keeps them from leaking into the rest of the function.

Can I write a one-line if in Go?

Not without braces. if ok return and if (ok) x = 1; are syntax errors. The shortest form is if ok { return }, and gofmt puts the body on its own line. Go also has no ternary operator, so a conditional value needs an if/else or a small helper function.

Why does Go use if err != nil everywhere?

Go has no exceptions. Functions that can fail return an error as their last result, and the caller checks it right away with if err != nil. The repetition is the price of having every failure point visible where it happens.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED