日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Go語言學習之條件語句使用詳解_Golang

作者:劍客阿良_ALiang ? 更新時間: 2022-06-14 編程語言

1、if...else判斷語法

語法的使用和其他語言沒啥區(qū)別。

樣例代碼如下:

// 判斷語句
func panduan(a int) {
    if a > 50 {
        fmt.Println("a > 50")
    } else if a < 30 {
        fmt.Println("a < 30")
    } else {
        fmt.Println("a <= 50 and a >= 30")
    }
}
 
func main() {
    panduan(120)
}

執(zhí)行結果

a > 50

2、if嵌套語法

樣例代碼如下

//嵌套判斷
func qiantao(b, c uint) {
    if b >= 100 {
        b -= 20
        if c > b {
            fmt.Println("c OK")
        } else {
            fmt.Println("b OK")
        }
    }
}

執(zhí)行結果

c OK

3、switch語句

兩種寫法,不需要加break。

樣例代碼如下

//switch使用
func test_switch() {
    var a uint = 90
    var result string
    switch a {
    case 90:
        result = "A"
    case 80, 70, 60:
        result = "B"
    default:
        result = "C"
    }
    fmt.Printf("result: %v\n", result)
    switch {
    case a > 90:
        result = "A"
    case a <= 90 && a >= 80:
        result = "B"
    default:
        result = "C"
    }
    fmt.Printf("result: %v\n", result)
 
}

執(zhí)行結果

result: A ? ? ? ? ? ? ?
result: B ?

注意

1、可是在switch后面加變量,后面的case主要做匹配判斷。也可以直接使用switch{},case直接對關系運算結果做匹配。

2、 case中可以選擇匹配多項。

4、類型switch語句

switch語句可以使用type-switch進行類型判斷,感覺很實用的語法。

樣例代碼如下

//測試類型switch
func test_type_switch() {
    var x interface{}
    x = 1.0
    switch i := x.(type) {
    case nil:
        fmt.Printf("x type = %T\n", i)
    case bool, string:
        fmt.Printf("x type = bool or string\n")
    case int:
        fmt.Printf("x type = int\n")
    case float64:
        fmt.Printf("x type = float64\n")
    default:
        fmt.Printf("未知\n")
    }
}

執(zhí)行結果

x type = float64 ? ??

注意

1、interface{}可以表示任何類型。

2、語法格式變量.(type)

5、fallthrough關鍵字使用

使用fallthrough關鍵字會強制執(zhí)行后面的case語句內容,不管時候觸發(fā)該case條件。

樣例代碼如下

// 測試fallthrough
func test_fallthrough() {
    a := 1
    switch {
    case a < 0:
        fmt.Println("1")
        fallthrough
    case a > 0:
        fmt.Println("2")
        fallthrough
    case a < 0:
        fmt.Println("3")
        fallthrough
    case a < 0:
        fmt.Println("4")
    case a > 0:
        fmt.Println("5")
        fallthrough
    case a < 0:
        fmt.Println("6")
        fallthrough
    default:
        fmt.Println("7")
    }
}

執(zhí)行結果

2 ? ? ? ? ? ? ? ? ? ? ?
3 ? ? ? ? ? ? ? ? ? ? ?
4 ?

注意

1、如果一旦在往下執(zhí)行case內容中不存在fallthrough,則會停止繼續(xù)往下執(zhí)行case內容。?

小結

我看到還有個select語句,需要和chan關鍵字進行配合使用,沒不了解,后面先研究一下chan關鍵字。

原文鏈接:https://blog.csdn.net/zhiweihongyan1/article/details/124169432

欄目分類
最近更新