Module lessons (1/5)
if, else and init statements
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 / elsebranches 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
- 1Basic syntax without parentheses
- 2The init statement before the condition
- 3Shadowing in the init statement
- 4No ternary operator
- 5Guided practice
- 6Check for understanding
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.