if, for, switch & defer

One loop keyword, switch without fallthrough, if with a short statement, and defer for cleanup.

Go has only one loop, for, which covers counted loops, while loops and infinite loops. switch does not fall through by default, and defer schedules cleanup code to run when the function returns.

Control flow

if v, err := strconv.Atoi("42"); err == nil { ... }: the variables exist only inside the if.

for i := 0; i < 3; i++ is the classic loop; for n < 1000 is a while loop; for { } loops forever.

switch with no value acts like an if-else chain; each case ends automatically.

Deferred calls run when main returns, last-deferred first.

defer in practice

for _, f := range files { fh, _ := os.Open(f); defer fh.Close() }

Close each file inside the loop, or move the body into a function

Deferred calls run when the function returns, not at the end of each iteration, so this keeps every file open until the loop's function ends.

Does Go's switch fall through to the next case?

No; each case ends automatically. Use the fallthrough keyword explicitly if you need it.