基本语法
// 最基本形式
if 条件 {
// 条件为 true 时执行
}
// 带 else
if 条件 {
// true 时执行
} else {
// false 时执行
}
// 带 else if
if 条件1 {
// 条件1 为 true
} else if 条件2 {
// 条件1 为 false,条件2 为 true
} else {
// 全部为 false
}
条件运算符举例
等于 ==
name := "Alice"
if name == "Alice" {
fmt.Println("Hello Alice!")
}
if name == "Bob" {
fmt.Println("Hello Bob!")
} else {
fmt.Println("You are not Bob")
}
不等于 !=
role := "admin"
if role != "admin" {
fmt.Println("Access denied")
} else {
fmt.Println("Welcome admin")
}
大于 >
age := 18
if age > 17 {
fmt.Println("You can vote")
}
score := 85
if score > 90 {
fmt.Println("Grade A")
} else if score > 80 {
fmt.Println("Grade B")
} else {
fmt.Println("Grade C or below")
}
小于 <
temperature := 30
if temperature < 35 {
fmt.Println("It's cool outside")
}
price := 150
budget := 120
if price < budget {
fmt.Println("I can buy it")
} else {
fmt.Println("Too expensive")
}
大于等于 >=
age := 65
if age >= 65 {
fmt.Println("You can retire")
}
points := 75
if points >= 70 {
fmt.Println("Pass")
} else {
fmt.Println("Fail")
}
小于等于 <=
speed := 55
if speed <= 60 {
fmt.Println("Speed OK")
} else {
fmt.Println("Speeding!")
}
items := 15
if items <= 10 {
fmt.Println("Need to restock soon")
} else {
fmt.Println("Stock is fine")
}
组合条件:&&(与)、||(或)
age := 16
hasPermission := true
if age >= 18 && hasPermission {
fmt.Println("Allowed")
} else {
fmt.Println("Not allowed")
}
if age >= 65 || role == "VIP" {
fmt.Println("Special access granted")
}
Go 特色:if 中声明变量
if score := calculateScore(); score >= 90 {
fmt.Println("Excellent:", score)
} else if score >= 70 {
fmt.Println("Good:", score)
} else {
fmt.Println("Needs improvement:", score)
}
if file, err := os.Open("data.txt"); err != nil {
fmt.Println("Error opening file:", err)
} else {
defer file.Close()
}
条件不需要括号,但大括号必须
if x > 0 {
fmt.Println("positive")
}
if (x > 0) {
fmt.Println("positive")
}
if x > 0
fmt.Println("positive")
运算符总结
| 运算符 |
含义 |
示例 |
结果为 true 的条件 |
== |
等于 |
a == b |
a 等于 b |
!= |
不等于 |
a != b |
a 不等于 b |
> |
大于 |
a > b |
a 大于 b |
< |
小于 |
a < b |
a 小于 b |
>= |
大于等于 |
a >= b |
a 大于或等于 b |
<= |
小于等于 |
a <= b |
a 小于或等于 b |
&& |
与 |
a > 0 && b > 0 |
a 和 b 都大于 0 |
|| |
或 |
a > 0 || b > 0 |
a 或 b 至少一个大于 0 |
! |
非 |
!a |
a 为 false |
常见陷阱
if name == "Alice" {
if isValid {
if isValid == true {
if 0 < x < 10 {
if x > 0 && x < 10 {