Golang教程:(八)if else 語句

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

原文:https://golangbot.com/if-statement/

這是本Golang系列教程的第八篇。

if 是一個條件陳述式。if 語句的文法為:

if condition {  }

如果 conditiontrue,那麼就執行 {} 之間的代碼。

與其它語言(如C)不同,即使 {} 之間只有一條語句,{} 也是必需的。

if 語句後面可以接可選的 else ifelse 語句:

if condition {  } else if condition {} else {}

if 後面可以接任意數量的 else if 語句。condition 的求值由上到下依次進行,直到某個 if 或者 else if 中的 conditiontrue 時,執行相應的代碼塊。如果沒有一個 conditontrue,則執行 else 中的代碼塊。

讓我們寫一個簡單的程式來判斷一個數是奇數還是偶數:

package mainimport (      "fmt")func main() {      num := 10    if num % 2 == 0 { //checks if number is even        fmt.Println("the number is even")     }  else {        fmt.Println("the number is odd")    }}

if num % 2 == 0 這條語句檢測一個數除以 2 的餘數是否為 0,如果是則輸出:"the number is even",否則輸出:"the number is odd"。上面的程式輸出:the number is even

if 語句還有如下的變體。這種形式的 if 語句先執行 statement,然後再判斷 conditon

if statement; condition {  }

讓我們用這種形式的 if 改寫上面的程式:

package mainimport (      "fmt")func main() {      if num := 10; num % 2 == 0 { //checks if number is even        fmt.Println(num,"is even")     }  else {        fmt.Println(num,"is odd")    }}

在上面的程式中, numif 語句中初始化。需要注意的一點是,num 只能在 ifelse 裡面進行訪問,即 num 的範圍僅限於 if else 塊中。如果我們試圖在 ifelse 之外訪問 num,編譯器將報錯。

讓我們用 else if 再寫一個程式:

package mainimport (      "fmt")func main() {      num := 99    if num >= 0 && num <= 50 {        fmt.Println("number is greater than 50")    } else if num >= 51 && num <= 100 {        fmt.Println("number is between 51 and 100")    } else {        fmt.Println("number is greater than 100")    }}

上面的程式中 else if num >= 51 && num <= 100true,因此程式的輸出為:number is between 51 and 100

if else 語句的介紹到此結束。感謝閱讀。

目錄
上一篇:Golang教程:(七)包
下一篇:Golang教程:(九)迴圈語句

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.