- 原文地址:Part 8: if else statement
- 原文做者:Naveen R
- 译者:咔叽咔叽 转载请注明出处。
if
是条件语句,语法为,golang
if condition {
}
复制代码
若是condition
为true
,介于{}
之间的代码块将被执行。c#
与 C 之类的其余语言不一样,即便{}
之间只有一个语句,{}
也是强制性须要的。less
else if
和else
对于if
来讲是可选的。spa
if condition {
} else if condition {
} else {
}
复制代码
if else
的数量不受限制,它们从上到下判断条件是否为真。若是if else
或者if
的条件为true
,则执行相应的代码块。若是没有条件为真,则执行else
的代码块。code
让咱们写一个简单的程序来查找数字是奇数仍是偶数。get
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")
}
}
复制代码
if num % 2 == 0
语句检查将数字除以 2 的结果是否为零。若是是,则打印"the number is even"
,不然打印"the number is odd"
。在上面的程序中,将打印the number is even
。string
if
变量还能够包含一个可选的statement
,它在条件判断以前执行。语法为it
if statement; condition {
}
复制代码
让咱们使用上面的语法重写程序,判断数字是偶数仍是奇数。io
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")
}
}
复制代码
在上面的程序中,num
在if
语句中初始化。须要注意的一点是,num
仅可从if
和else
内部访问。即num
的范围仅限于if else
代码块,若是咱们尝试从if
或else
外部访问num
,编译器会报错。
让咱们再写一个使用else if
的程序。
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 num >= 51 && num <= 100
为真,那么程序将输出number is between 51 and 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")
}
}
复制代码
在上面的程序中,else
语句没有在if
语句接近}
以后的同一行开始。相反,它从下一行开始。 Go 中不容许这样作,若是运行此程序,编译器将输出错误,
main.go:12:5: syntax error: unexpected else, expecting }
复制代码
缘由是 Go 是自动插入分号的。你能够从这个连接查看有关分号插入规则的信息https://golang.org/ref/spec#Semicolons。
在规则中,若是}
是该行最后的一个标记,go 将会在以后插入分号。所以,在if
语句的}
以后会自动插入分号。
因此咱们的程序实际是下面这样的,
if num%2 == 0 {
fmt.Println("the number is even")
}; //semicolon inserted by Go
else {
fmt.Println("the number is odd")
}
复制代码
由于{...} else {...}
是一个语句,因此在它的中间不该该有分号。所以,须要将else
放在`}后的同一行中。
我已经经过在if
语句的}
以后插入else
来重写程序,以防止自动分号插入。
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")
}
}
复制代码
如今编译器能够正常执行了。