Go语言编程入门超级指南

2020-01-28 12:01:04王冬梅

    var b1 = true
    b2 := false
    fmt.Printf("推导类型:b1[%t], b2[%t]n", b1, b2)

    const age int = 20
    const pi float32 = 3.1415926
    fmt.Printf("常量:age[%d], pi[%f]n", age, pi)
}

3.2 控制语句

作为最基本的语法要素,Golang的各种控制语句也是特点鲜明。在对C继承发扬的同时,也有自己的想法融入其中:

if/switch/for的条件部分都没有圆括号,但必须有花括号。
switch的case中不需要break。《C专家编程》里也“控诉”了C的fall-through问题。既然90%以上的情况都要break,为何不将break作为case的默认行为?而且编程语言后来者也鲜有纠正这一问题的。
switch的case条件可以是多个值。
Golang中没有while。

package main

import "fmt"

/**
 * testIf: x[2] is even
 * testIf: x[3] is odd
 *
 * testSwitch: One
 * testSwitch: Two
 * testSwitch: Three, Four, Five [3]
 * testSwitch: Three, Four, Five [4]
 * testSwitch: Three, Four, Five [5]
 *
 * 标准模式:[0] [1] [2] [3] [4] [5] [6]
 * While模式:[0] [1] [2] [3] [4] [5] [6]
 * 死循环模式:[0] [1] [2] [3] [4] [5] [6]
 */
func main() {
    testIf(2)
    testIf(3)
    testSwitch(1)
    testSwitch(2)
    testSwitch(3)
    testSwitch(4)
    testSwitch(5)
    testFor(7)
}

func testIf(x int) {
    if x % 2 == 0 {
        fmt.Printf("testIf: x[%d] is evenn", x)
    } else {
        fmt.Printf("testIf: x[%d] is oddn", x)
    }
}

func testSwitch(i int) {
    switch i {
        case 1:
            fmt.Println("testSwitch: One")
        case 2:
            fmt.Println("testSwitch: Two")
        case 3, 4, 5:
            fmt.Printf("testSwitch: Three, Four, Five [%d]n", i)
        default:
            fmt.Printf("testSwitch: Invalid value[%d]n", i)
    }
}

func testFor(upper int) {
    fmt.Print("标准模式:")
    for i := 0; i < upper; i++ {