Control Flow in Golang

If statement

if x > 6 {
	
} else if x < 2 {

} else {

}
  • Avoid one line if
  • Omit else when there is break, continue, goto, or return in if-statement
f, err := os.Open(name)
if err != nil {
    return err
}
d, err := f.Stat()
if err != nil {
    f.Close()
    return err
}
codeUsing(f, d)
💡
No ternary if in Golang like using ?

Loop (only for-loop)

// for loop
for i := 0; i < 5; i++ {
	fmt.Println(i)
}

// simulate while loop
i := 0
for i< 5 {
	fmt.Println(i)
	i++
}

// just like enumerate in Python
for index, value := range a {
	fmt.Println(index, value)
}

for key, value := range vertices {
	fmt.Println(key, value)
}
  • Something like for ch in string in Python
for pos, char := range "日本\x80語" { // \x80 is an illegal UTF-8 encoding
    fmt.Printf("character %#U starts at byte position %d\n", char, pos)
}

/*
character U+65E5 'æ—¥' starts at byte position 0
character U+672C '本' starts at byte position 3
character U+FFFD '�' starts at byte position 6
character U+8A9E '語' starts at byte position 7
*/

Assign multiple variables in one line

// Reverse a
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
    a[i], a[j] = a[j], a[i]
}

Switch

  • Cases are evaluated from top to bottom
  • Evaluate boolean condition
func unhex(c byte) byte {
    switch {
    case '0' <= c && c <= '9':
        return c - '0'
    case 'a' <= c && c <= 'f':
        return c - 'a' + 10
    case 'A' <= c && c <= 'F':
        return c - 'A' + 10
    }
    return 0
}
  • Evaluate if a variable == something
func shouldEscape(c byte) bool {
    switch c {
    case ' ', '?', '&', '=', '#', '+', '%':
        return true
    }
    return false
}
  • break can work for switch and loop, but continue only works for loop
  • Specify the label to break or continue the outer one
Loop: // a label to indicating for-loop
	for n := 0; n < len(src); n += size {
		switch {
		case src[n] < sizeOne:
			if validateOnly {
				break
			}
			size = 1
			update(src[n])

		case src[n] < sizeTwo:
			if n+1 >= len(src) {
				err = errShortInput
				break Loop
			}
			if validateOnly {
				break
			}
			size = 2
			update(src[n] + src[n+1]<<shift)
		}
	}

Type Switch

package main

import "fmt"

func do(i interface{}) {
	// type switch
	switch v := i.(type) {
	case int:
		fmt.Printf("Twice %v is %v\n", v, v*2)
	case string:
		fmt.Printf("%q is %v bytes long\n", v, len(v))
	default:
		fmt.Printf("I don't know about type %T!\n", v)
	}
}

func main() {
	do(21)
	do("hello")
	do(true)
}