Golang學習筆記-1.8 switch語句

來源:互聯網
上載者:User

本文系第八篇Golang語言學習教程
switch是一個條件陳述式,用於將運算式的值與可能匹配的選項列表進行比較,並根據情況執行相應代碼。是替代if else的常用方式。

下面通過講解一個簡單的運算程式來瞭解switch語句

package mainimport "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篇

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.