Making Decisions
8 min · Go
Run different code depending on whether something is true.
Enemy 1 of 5
if / else without parentheses
An if statement runs its { } block only when the condition evaluates to true. Go deliberately drops the parentheses around the condition that C, C++, and C# all require — you write if temperature > 20 { ... }, not if (temperature > 20) { ... }. Leaving them in isn't a syntax error exactly, but Go's own formatting tool (gofmt) will complain, since idiomatic Go simply doesn't use them.
Curly braces, on the other hand, are not optional in Go the way they sometimes are in C-family languages for single-statement blocks — every if and else body must be wrapped in { }, even for a single line. This is a deliberate design choice that eliminates a well-known class of bugs where an unbraced if only applied to the very next line.
else runs when the if's condition was false, giving you the "otherwise" branch. Comparisons use the same familiar operators: > , < , >= , <= , == , != .
Loading editor...