Control structures
Control structures are used to control the flow of program execution. The most common forms are the if
statements, for
loops, and switch
statements. Go also supports the goto
statement, but should be reserved for cases of extreme performance and not used regularly. Let's look briefly at each of these to understand the syntax.
if
The if
statement comes with the if
, else if
, and else
clauses, just like most other languages. The one interesting feature that Go has is the ability to put a statement before the condition, creating temporary variables that are discarded after the if
statement has completed.
This example demonstrates the various ways to use an if
statement:
package main import ( "fmt" "math/rand" ) func main() { x := rand.Int() if x < 100 { fmt.Println("x is less than 100.") } if x < 1000 { fmt.Println("x is less than 1000.") } else if x < 10000 { fmt.Println("x is less than 10,000.") } else { fmt.Println...