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

·  阅读 1006

`if`是条件语句，语法为，

``````if condition {
}

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

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

`if else`的数量不受限制，它们从上到下判断条件是否为真。如果`if else`或者`if`的条件为`true`，则执行相应的代码块。如果没有条件为真，则执行`else`的代码块。

``````package main

import (
"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 main

import (
"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 main

import (
"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 main

import (
"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 Go
else {
fmt.Println("the number is odd")
}

``````package main

import (
"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