57

Golang学习笔记-1.8 switch语句

 5 years ago
source link: https://studygolang.com/articles/13615?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文系第八篇Golang语言学习教程

switch 是一个条件语句,用于将表达式的值与可能匹配的选项列表进行比较,并根据情况执行相应代码。是替代 if else 的常用方式。

下面通过讲解一个简单的运算程序来了解 switch 语句

package main

import "fmt"

func eval(a, b int, op string) int { //定义eval函数,输入三个值 a, b, op 输出类型为 int
    var result int
    switch op {   // op 为表达式,将 op 的值与下面 case 比较
    case "+":  //若 op 值为 + , 则将 result 赋值 a + b 以此类推
        result = a + b
    case "-":
        result = a - b
    case "*":
        result = a * b
    case "/":
        result = a / b
    default:  //如果输入没有以上匹配的字符,则属于默认情况,运行默认情况
        fmt.Println("unsupported operator:" + op)  //输出不识别 op 值的报错

    }
    return result
}

func main(){
    fmt.Println(
        eval(10, 4, "+"),
        eval(15, 6, "-"),
        eval(2, 4, "*"),
        eval(100, 4, "/"),
    )
}

在以上程序中, switch 将 op 的值作为表达式,与 case 比较。op值若为 "+" ,所以匹配到第一个 case ,给result赋值后退出 case 。以此类推

若op输入的值没有匹配到,则属于默认情况, 运行默认代码 ,本程序输出报错。

以上程序执行结果为 : 14 9 8 25

多表达式判断

通过用 , 逗号隔开,一个 case 中可以写多个表达式

func main(){
    letter := "i"
    switch letter {
    case "a", "o", "e", "i", "u":  //用 "," 逗号分隔,多个表达式
        fmt.Println(letter, "is in vowel")
    default:
        fmt.Println(letter, "is not in vowel")
    }
}

在 case a , e , i , o , u : 这一行中,列举了所有的元音。只要匹配该项,则将输出 i is in vowel

无表达式的switch

switch中,表达式是可选的,如果省略表达式,则这个switch语句等同于 switch true ,每个 case 都被认定为有效,执行相应的代码块。

func main(){
    num := 79
    switch  {  //省略表达式
    case num >= 0 && num <= 50:
        fmt.Println("num is greater than 0 and less than 50")
    case num >= 50 && num <= 100:
        fmt.Println("num is greater than 50 and less than 100")
    case num >= 100:
        fmt.Println("num is greater than 100")
    }

}

在以上程序中,num值为79,省略表达式,则匹配每个case,直至结束。

以上程序输出输出: num is greater than 50 and less than 100

Fallthrough语句

在 Go 中,每执行完一个 case 后,会从 switch 语句中跳出来,不再做后续 case 的判断和执行。使用 fallthrough 语句可以在已经执行完成的 case 之后,把控制权转移到下一个 case 的执行代码中。

还是上一个程序,但如果将 num 赋值100,只会匹配到第二个case后跳出,我们加上 fallthrough 后查看效果。

func main(){
    num := 79
    switch  {  //省略表达式
    case num >= 0 && num <= 50:
        fmt.Println("num is greater than 0 and less than 50")
    case num >= 50 && num <= 100:
        fmt.Println("num is greater than 50 and less than 100")
        fallthrough
    case num >= 100:
        fmt.Println("num is greater than 100")
    }

}

num := 100 ,可以配置第二个case,也可以匹配第三个,通过 fallthrough ,我们成功的同时匹配到了两个case。

注意: fallthrough 语句应该是 case 子句的最后一个语句。不要写在case语句的中间。

以上为学习Golang switch篇


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK