本文系第七篇Golang語言學習教程
if-else
if 是條件陳述式
文法如下:
if condition { }
如果condition為真,則執行{}之間的代碼
Go還有可選的else if和else語句
if condition {} else if condition {} else {}
else if語句可以有任意數量,從上到下判斷。
如果if 或else if判斷為真,則執行相應的{}中代碼。
如果沒有條件為真,則自動執行else代碼
先寫一個簡單的判斷數字是奇數偶數的程式:
package mainimport "fmt"func main(){ num := 21 if num % 2 == 0 { //如果 num 取 2 的餘數為 0 fmt.Println("this number is env") //輸出this number is env } else { fmt.Println("this number is odd") //若餘數不為 0 ,則輸出this number is env }}
if num % 2 == 0用來檢測num 取 2 的餘數是否為 0 。
以上程式輸出:num 取 2 的餘數為 0
if 還有另外一種形式,它包含一個statement可選部分,該條件在條件判斷前運行。
文法如下:
if statement; condition { }
重寫判斷奇偶數的程式:
package mainimport "fmt"func main(){ if numb := 21; numb % 2 == 0 { fmt.Println("this number is env") } else { fmt.Println("this number is odd") }}
以上程式中,if是在條件中賦值,所以條件中賦值的變數numb範圍只能在這個if代碼塊中。 如果試圖從外部的if或 else 中訪問numb,編譯器不會通過。
注意:
else 一定要在 if 語句 } 之後,否則會報錯
條件陳述式還有switch語句,下一節將學習switch語句。
以上為學習Golang if-else篇