Skip to main content
Module 2 · Lesson 1 of 56/50 in the course~10 min
Module lessons (1/5)

if, else and init statements

Lesson preview5 hands-on exercises readyCourse Go · Module 2 — Flow Control

The form if v := f(); v > 0 { ... } and why the ternary operator does not exist in Go.

What you'll learn in this lesson

  • Write if / else if / else branches respecting the boolean obligation and Go's braces.
  • Limit the scope of temporary variables with the init statement (if v := expr; cond).
  • Avoid accidental shadowing between external variables and variables declared in init.

Overview

In Go the syntax of if strips the parentheses around the condition but still requires the curly braces { ... }. The condition must strictly have type bool: non-zero numbers or non-empty strings are never implicitly converted to true.

You can prefix a short statement separated from ; before the Boolean condition: the variable thus declared lives only inside if and its possible branches else if / else:

Sections covered in this lesson

  1. 1Basic syntax without parentheses
  2. 2The init statement before the condition
  3. 3Shadowing in the init statement
  4. 4No ternary operator
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 2 — Flow Control

Unlock "if, else and init statements" and the full Course Go curriculum

The form `if v := f(); v > 0 { ... }` and why the ternary operator does not exist in Go.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Go plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.