# [译] part 8: golang if else 语句

https://juejin.im/post/5cbf2c2f5188254c2d27f6f7

if是条件语句，语法为，

if condition {  }

else ifelse对于if来说是可选的。

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

if else的数量不受限制，它们从上到下判断条件是否为真。如果if else或者if的条件为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")    }}

Run in playground

if num % 2 == 0语句检查将数字除以 2 的结果是否为零。如果是，则打印"the number is even"，否则打印"the number is odd"。在上面的程序中，将打印the number is even

if变量还可以包含一个可选的statement，它在条件判断之前执行。语法为

if statement; condition {  }

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")    }}

Run in playground

package mainimport (      "fmt")func main() {      num := 99    if num <= 50 {        fmt.Println("number is less than or equal to 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语句结束的}之后的同一行开始。如果不是，编译器会报错。

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")    }}

Run in playground

main.go:12:5: syntax error: unexpected else, expecting }

if num%2 == 0 {        fmt.Println("the number is even") };  //semicolon inserted by Goelse {        fmt.Println("the number is odd")}

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

Run in playground