本文是golang教程的第8节课。
if是一个条件语句。if语句语法是:
if condition {
}
如果条件condition为true,{和}之间的代码模块将被执行。
和其他语言不同,大括号{}是必须的,即使大括号{}里面只有一条语句。
if语句还有可选的else if和else部分。
if condition {
} else if condition {
} else {
}
else ififelse ifelse
让我们编写一个简单的程序来检测一个数字是奇数还是偶数。
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 == 0the number is even
ifstatement
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")
}
}
numifnumifelsenumifelseifelsenum
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 <= 100number is between 51 and 100
一个注意点
elseif}
让我们通过以下程序来理解它。
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")
}
}
elseif}
main.go:12:5: syntax error: unexpected else, expecting }
出错的原因是 Go 语言的分号是自动插入。你可以在这里阅读分号插入规则 https://golang.org/ref/spec#Semicolons。
}}
实际上我们的程序变成了
if num%2 == 0 {
fmt.Println("the number is even")
}; //semicolon inserted by Go
else {
fmt.Println("the number is odd")
}
分号插入之后。从上面代码片段可以看出第三行插入了分号。
if{…} else {…}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")
}
}
现在编译器会很开心,我们也一样 。
本章教程到此告一段落了,感谢您的阅读,欢迎您的任何评论和反馈。