A Tour of Go - Basics: Flow control statements: for, if, else, switch and defer Flashcards
How many loop constructs are there in Go?
one
What is a for loop?
The basic for loop has three components separated by semicolons:
- the init statement: executed before the first iteration
- the condition expression: evaluated before every iteration
- the post statement: executed at the end of every iteration
The init statement will often be a short variable declaration, and the variables declared there are visible only in the scope of the for statement.
The loop will stop iterating once the boolean condition evaluates to false.
What is a forever loop?
for { }
Which for loop components are optional?
The init statement and the post statement. When omitted the semi-colons can be dropped.
Give an example of a simple if statement?
if a == b { fmt.Println("a equals b") }
Give an example of an if with a short statement?
if v := math.Pow(x, n); v < lim { return v }
Give and example of an if else statement
if v := math.Pow(x, n); v < lim { return v } else { fmt.Printf("%g >= %g\n", v, lim) }
A switch statement is a …
A switch statement is a shorter way to write a sequence of if - else statements. It runs the first case whose value is equal to the condition expression.
Switch cases evaluate cases ….
Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
Go’s switch cases ….
Go’s switch cases need not be constants, and the values involved need not be integers.
Switch without a condition is …
Switch without a condition is the same as switch true.
This construct can be a clean way to write long if-then-else chains.
Give an example of a switch statement
switch os := runtime.GOOS; os { case "darwin": fmt.Println("OS X.") case "linux": fmt.Println("Linux.") default: fmt.Printf("%s.\n", os) } }
A defer statement ….
A defer statement defers the execution of a function until the surrounding function returns.
The deferred call’s arguments ….
The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
Deferred function calls are ….
Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order.