這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
原文:https://golangbot.com/if-statement/
這是本Golang系列教程的第八篇。
if 是一個條件陳述式。if 語句的文法為:
if condition { }
如果 condition 為 true,那麼就執行 { 和 } 之間的代碼。
與其它語言(如C)不同,即使 {} 之間只有一條語句,{} 也是必需的。
if 語句後面可以接可選的 else if 和 else 語句:
if condition { } else if condition {} else {}
if 後面可以接任意數量的 else if 語句。condition 的求值由上到下依次進行,直到某個 if 或者 else if 中的 condition 為 true 時,執行相應的代碼塊。如果沒有一個 conditon 為 true,則執行 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") }}
在上面的程式中, num 在 if 語句中初始化。需要注意的一點是,num 只能在 if 和 else 裡面進行訪問,即 num 的範圍僅限於 if else 塊中。如果我們試圖在 if 或 else 之外訪問 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 <= 100 為 true,因此程式的輸出為:number is between 51 and 100。
if else 語句的介紹到此結束。感謝閱讀。
目錄
上一篇:Golang教程:(七)包
下一篇:Golang教程:(九)迴圈語句