# if else条件语句

本节介绍Golang中的条件语句`if else`。`if`语句的语法如下：

```go
if condition {

}
```

`condition`条件满足时执行大括号中的代码块。Golang比`JavaScript`等语言更严格，即使大括号中仅有一条语句，大括号也不能省略。

跟大多数编程语言类似，Golang`if`条件语句也支持`else if`和`else`：

```go
if condition {

} else if condition {

} else {

}
```

当然，`else if`语句可以存在多个。

当`if`和`else if`任何一个条件判断通过时，执行对应的代码块得，否则就说明所有这些判断条件都不通过，那么就执行`else`对应的代码块。

我们写一个程序来判断一个数字是奇数还是偶数。

```go
package main

import "fmt"

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

[Go Playground在线运行](https://play.golang.org/p/y3k-8D3RJA-) 这里的`if num % 2 == 0`语句判断`num`对2求模的余数是否是0。如果是，那么就打印"the number is even"，否则就打印"the number is odd"。由于这里`num`赋值为10，是偶数，因此这段程序会打印`the number is even`。

Golang中的`if`有个变体，可以在判断条件`condition`之前加一个语句，语法如下：

```go
if statement; condition {

}
```

我们用这种写法重构下前面的程序。

```go
package main

import "fmt"

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

[Go Playground在线运行](https://play.golang.org/p/1fLD_DyAkf4) 这种写法的不同点在于，`num`变量初始化是在`if`语句内完成的，因此`num`变量的作用域也仅限与`if`语句(当然也包括`else`)内，因此也就无法在该`if else`语句外访问`num`变量。

我们现在写一个程序来体验下`else if`的用法。

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

[Go Playground在线运行](https://play.golang.org/p/1PmKCJt5meX) 这里由于`num`初始化赋值为`99`，因此`num >= 51 && num <= 100`条件判断通过，因此打印输出`number is between 51 and 100`。

#### 防坑指南

Golang中条件语句的`else`不能另起一行，必须跟在`}`符号后面，否则编译会报错。

```go
package main

import "fmt"

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

[Go Playground在线运行](https://play.golang.org/p/E5BAZxmHu2l) 这段代码里`else`子句没有紧跟在`}`符号后面，而是另起新的一行，因此会报错：

```
syntax error: unexpected else, expecting }
```

为什么会这样呢？原因是因为Golang会在位于行尾的`}`符号后面自动补一个分号，具体可以参考这里：<https://golang.org/ref/spec#Semicolons>。

这时我们的代码会变成：

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

由于`if else`一个完整的语句，在中间插入了`;`当然报错了。起初可能不太习惯，不过换个角度看，这一点反倒使得Golang的语法更加严格，要求大家写的代码也更加一致。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sunwenfei.gitbook.io/sunwenfei/golang/golang-ji-chu-jiao-cheng/tiao-jian-xun-huan/if-else-tiao-jian-yu-ju.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
