Go -- 判断if/else、分支switch、数组

if/else

package main
import "fmt"
func main() {
    //这里是一个基本的例子。

    if 7%2 == 0 {
        fmt.Println("7 is even")
    } else {
        fmt.Println("7 is odd")
    }
    //你可以不要 else 只用 if 语句。

    if 8%4 == 0 {
        fmt.Println("8 is divisible by 4")
    }
    //在条件语句之前可以有一个语句;任何在这里声明的变量都可以在所有的条件分支中使用。

    if num := 9; num < 0 {
        fmt.Println(num, "is negative")
    } else if num < 10 {
        fmt.Println(num, "has 1 digit")
    } else {
        fmt.Println(num, "has multiple digits")
    }
}

注意,在 Go 中,你可以不适用圆括号,但是花括号是需要的。

Go 里没有三元运算符,所以即使你只需要基本的条件判断,你仍需要使用完整的 if 语句

Switch分支结构

package main
import "fmt"
import "time"
func main() {
    //一个基本的 switch。

    i := 2
    fmt.Print("write ", i, " as ")
    switch i {
    case 1:
        fmt.Println("one")
    case 2:
        fmt.Println("two")
    case 3:
        fmt.Println("three")
    }
    //在一个 case 语句中,你可以使用逗号来分隔多个表达式。在这个例子中,我们很好的使用了可选的default 分支。

    switch time.Now().Weekday() {
    case time.Saturday, time.Sunday:
        fmt.Println("it's the weekend")
    default:
        fmt.Println("it's a weekday")
    }
    //不带表达式的 switch 是实现 if/else 逻辑的另一种方式。这里展示了 case 表达式是如何使用非常量的。

    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Println("it's before noon")
    default:
        fmt.Println("it's after noon")
    }
}

数组

在go中,数组是固定长度的数列。


package main
import "fmt"
func main() {
    //这里我们创建了一个数组 a 来存放刚好 5 个 int。元素的类型和长度都是数组类型的一部分。数组默认是零值的,对于 int 数组来说也就是 0。

    var a [5]int
    fmt.Println("emp:", a)
    //我们可以使用 array[index] = value 语法来设置数组指定位置的值,或者用 array[index] 得到值。

    a[4] = 100
    fmt.Println("set:", a)
    fmt.Println("get:", a[4])
    //使用内置函数 len 返回数组的长度

    fmt.Println("len:", len(a))
    //使用这个语法在一行内初始化一个数组

    b := [5]int{1, 2, 3, 4, 5}
    fmt.Println("dcl:", b)
    //数组的存储类型是单一的,但是你可以组合这些数据来构造多维的数据结构。

    var twoD [2][3]int
    for i := 0; i < 2; i++ {
        for j := 0; j < 3; j++ {
            twoD[i][j] = i + j
        }
    }
    fmt.Println("2d: ", twoD)
}

猜你喜欢

转载自blog.csdn.net/ZaberyJava/article/details/88637919