This is a creation in Article, where the information may have evolved or changed.
This is the Go second article in the series, which mainly introduces the various usages of if/else, switch and functions.
Series Finishing:
- Go Part I: Variables, constants, and enumeration types
If you are interested in the Go language itself, you can read my translation of the advantages, disadvantages and repulsive design of the go language.
If/else
// 声明可以先于条件,if 中的声明的变量只在此 if/else 有效if num := 9; num < 0 { } else if num < 10 { } else { }
Switch
// 普通 switchswitch time.Now().Weekday() { // 可以用逗号写多个值 case time.Saturday, time.Sunday: fmt.Println("It's the weekend") default: fmt.Println("It's the weekday")}// 无表达式额的 switchswitch { case t.Hour() < 12: fmt.Println("It's before noon") default: fmt.Println("It's after noon")}// 比较类型whatAmI := func(i interface{}) { switch t := i.(type) { case bool: fmt.Println("I'm a bool") case int: fmt.Println("I'm a int") default: fmt.Printf("Don't know type %T\n", t) }}whatAmI(true)whatAmI(1)whatAmI("hey")
Cycle
// 经典的循环for n := 0; n <= 5; n++ { if n % 2 == 0 { continue } fmt.Println(n)}// 只有条件for i <= 3 { fmt.Println(i) i = i + 1 }// 死循环for { fmt.Println("loop") break}
Actual test
Convert an integer to a binary representation
func convertToBin(v int) string { result := "" for ; v > 0; v /= 2 { result = strconv.Itoa(v % 2) + result } return result}
Function
// 闭包函数func apply(op func(int, int) int, a, b int) int { return op(a, b)}func main() { result := apply(func(i int, i2 int) int { return int(math.Pow(float64(i), float64(i2))) }, 2, 2) fmt.Println(result)}// 可变参数func sum(num ... int) int { var result = 0 for _, v := range num { result = result + v } return result}c := sum(1, 2, 3)fmt.Println(c)