Defer

defer statement defers execution of a function until the surrounding function returns.

package main
import "fmt"
func main() {
        defer fmt.Println("world")
        fmt.Println("hello")
}
# /usr/local/go/bin/go build defer-statement.go
# ./defer-statement
hello
world
            

if statement

a. Expression not surrounded by parentheses ( ) but the braces { } are required.
b. if statement can start with Short statement to execute before condition.
c. Variables declared in if statement are also avaiable in else block.

package main
import (
        "fmt"
        "math"
)
func main() {
        a := 1.1 
        if a < 4 {                              //1a
                fmt.Println("Hi")
        }

        b := 2.2
        if v := math.Pow(a, b); v < 4 {         //1b
                fmt.Println("There")
        } else {                                //1c
                fmt.Println(v)
        }
}
# /usr/local/go/bin/go build if-statement.go
# ./if-statement
Hi
There
            

switch

a. breaks statement is provided automatically in go
b. Unlike C,C++ swtich only runs the selected case, not all cases that follow
c. Switch cases, Need Not to be constants. values involved need not to be integers.

package main
import (
        "fmt"
        "runtime"
)
func main() {
        switch os := runtime.GOOS; os {
        case "darwin":
                fmt.Println("OS X")             //a. go provides break automatically
        case "linux":                           //c. switch case need not to be constants
                fmt.Println("Linux")
        case "ubuntu":
                fmt.Println("Ubuntu")
        default:
                fmt.Printf("%s.\n", os)
        }
}
# /usr/local/go/bin/go build switch.go
# ./switch
Linux