运算符 - Go 运算符详解
Go 提供了丰富的运算符用于各种计算和比较。理解运算符的优先级和特性是编写正确表达式的基础。
算术运算符
📝 基本算术运算
package main
import "fmt"
func main() {
a, b := 10, 3
// 基本运算
fmt.Printf("%d + %d = %d\n", a, b, a+b)
fmt.Printf("%d - %d = %d\n", a, b, a-b)
fmt.Printf("%d * %d = %d\n", a, b, a*b)
fmt.Printf("%d / %d = %d\n", a, b, a/b) // 整数除法
fmt.Printf("%d %% %d = %d\n", a, b, a%b) // 取余
// 浮点运算
x, y := 10.0, 3.0
fmt.Printf("%.2f / %.2f = %.2f\n", x, y, x/y)
// 自增自减
i := 0
i++ // i = 1
i-- // i = 0
// ❌ Go 没有 ++i 或 --i
// ❌ Go 没有自增自减表达式,只能是语句
}
比较运算符
📝 比较运算
package main
import "fmt"
func main() {
a, b := 10, 5
fmt.Printf("%d == %d: %v\n", a, b, a == b)
fmt.Printf("%d != %d: %v\n", a, b, a != b)
fmt.Printf("%d > %d: %v\n", a, b, a > b)
fmt.Printf("%d < %d: %v\n", a, b, a < b)
fmt.Printf("%d >= %d: %v\n", a, b, a >= b)
fmt.Printf("%d <= %d: %v\n", a, b, a <= b)
// 字符串比较 (字典序)
fmt.Println("apple" < "banana") // true
}
逻辑运算符
📝 逻辑运算
package main
import "fmt"
func main() {
a, b := true, false
fmt.Printf("true && false = %v\n", a && b)
fmt.Printf("true || false = %v\n", a || b)
fmt.Printf("!true = %v\n", !a)
// 短路求值
if false && expensive() {
// expensive() 不会被调用
}
if true || expensive() {
// expensive() 不会被调用
}
}
func expensive() bool {
fmt.Println("Expensive called")
return true
}
位运算符
📝 位运算
package main
import "fmt"
func main() {
a, b := 12, 5 // 1100, 0101
fmt.Printf("%d & %d = %d\n", a, b, a&b) // 0100 = 4
fmt.Printf("%d | %d = %d\n", a, b, a|b) // 1101 = 13
fmt.Printf("%d ^ %d = %d\n", a, b, a^b) // 1001 = 9
fmt.Printf("%d &^ %d = %d\n", a, b, a&^b) // 1000 = 8 (位清除)
// 移位
fmt.Printf("%d << 1 = %d\n", a, a<<1) // 24
fmt.Printf("%d >> 1 = %d\n", a, a>>1) // 6
}
赋值运算符
📝 复合赋值
package main
import "fmt"
func main() {
a := 10
a += 5 // a = a + 5 = 15
a -= 3 // a = a - 3 = 12
a *= 2 // a = a * 2 = 24
a /= 4 // a = a / 4 = 6
a %= 4 // a = a % 4 = 2
a <<= 2 // a = a << 2 = 8
a >>= 1 // a = a >> 1 = 4
a &= 3 // a = a & 3 = 0
a |= 5 // a = a | 5 = 5
a ^= 3 // a = a ^ 3 = 6
fmt.Printf("Result: %d\n", a)
}
📖 运算符优先级 (从高到低)
() [] -> .! + - ^ * & &^ ++ --* / % << >> & &^+ - | ^== != < <= > >=&&||