Go 语言运算符
算术、比较、逻辑、位运算、赋值,以及 Go 独有的 `&^`。
Key PointsGo 没有三元运算符,没有 `++` 前缀,`&^` 是「按位清零」。
算术
Go
a, b := 7, 3
fmt.Println(a+b, a-b, a*b, a/b, a%b)
fmt.Println(7.0 / 3.0)Output
10 4 21 2 1
2.3333333333333335Integer division truncates: 7/3 is 2, not 2.33. Make one operand a float for decimals. % works only on integers.
自增与赋值
Go
i := 1
i++ // 只能作为语句,不能 i = i++
fmt.Println(i)
// 复合赋值
x := 10
x += 5; fmt.Println(x)
x -= 3; fmt.Println(x)
x *= 2; fmt.Println(x)
x /= 4; fmt.Println(x)
x %= 4; fmt.Println(x)Output
2
15
12
24
6
2i++ is a statement, not an expression, so j := i++ will not compile, and there is no prefix ++i. A deliberate simplification that kills expressions like a = b++ + ++c.比较与逻辑
Go
fmt.Println(1 == 1, 1 != 2, 3 > 2, 3 <= 3)
fmt.Println(true && false, true || false, !true)
// 短路求值
var p *int
if p != nil && *p > 0 { // 安全:p 为 nil 时不会解引用
fmt.Println("正数")
}Output
true true true true
false true false位运算
| Op | Meaning | Example |
|---|---|---|
& | 按位与 | 6 & 3 → 2 |
| | 按位或 | 6 | 3 → 7 |
^ | 按位异或(二元)/ 取反(一元) | 6 ^ 3 → 5,^6 → -7 |
&^ | 按位清零:a &^ b = a & ^b | 6 &^ 3 → 4 |
<< >> | 左移 / 右移 | 1 << 3 → 8 |
Go
fmt.Println(6&3, 6|3, 6^3, 6&^3)
fmt.Println(1<<3, 16>>2)Output
2 7 5 4
8 4&^ is Go-specific, equal to a & (^b) — "clear the bits of a where b has 1s". Handy on permission bitmaps: perms = perms &^ WritePerm.
优先级
Text
5 * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 ||Only 5 levels, far simpler than C. When unsure, add parentheses — the Go community does not consider extra parens a sin.
算术
Go
a, b := 7, 3
fmt.Println(a+b, a-b, a*b, a/b, a%b)
fmt.Println(7.0 / 3.0)Output
10 4 21 2 1
2.3333333333333335整数除法直接截断,7/3 是 2 不是 2.33。想要小数必须至少一边是浮点。% 只对整数有效。
自增与赋值
Go
i := 1
i++ // 只能作为语句,不能 i = i++
fmt.Println(i)
// 复合赋值
x := 10
x += 5; fmt.Println(x)
x -= 3; fmt.Println(x)
x *= 2; fmt.Println(x)
x /= 4; fmt.Println(x)
x %= 4; fmt.Println(x)Output
2
15
12
24
6
2i++ 在 Go 里是语句不是表达式,所以 j := i++ 编译不过,也没有 ++i 这种前缀写法。这是刻意的简化,避免 a = b++ + ++c 这类歧义。比较与逻辑
Go
fmt.Println(1 == 1, 1 != 2, 3 > 2, 3 <= 3)
fmt.Println(true && false, true || false, !true)
// 短路求值
var p *int
if p != nil && *p > 0 { // 安全:p 为 nil 时不会解引用
fmt.Println("正数")
}Output
true true true true
false true false位运算
| 运算符 | 含义 | 例子 |
|---|---|---|
& | 按位与 | 6 & 3 → 2 |
| | 按位或 | 6 | 3 → 7 |
^ | 按位异或(二元)/ 取反(一元) | 6 ^ 3 → 5,^6 → -7 |
&^ | 按位清零:a &^ b = a & ^b | 6 &^ 3 → 4 |
<< >> | 左移 / 右移 | 1 << 3 → 8 |
Go
fmt.Println(6&3, 6|3, 6^3, 6&^3)
fmt.Println(1<<3, 16>>2)Output
2 7 5 4
8 4&^ 是 Go 独有的运算符,等价于 a & (^b),含义是「把 a 里 b 为 1 的那些位清掉」。操作权限位图时非常顺手:perms = perms &^ WritePerm。
优先级
Text
5 * / % << >> & &^
4 + - | ^
3 == != < <= > >=
2 &&
1 ||只有 5 层,比 C 简单得多。拿不准就加括号——Go 社区不认为多写括号是坏事。