Go 语言运算符

算术、比较、逻辑、位运算、赋值,以及 Go 独有的 `&^`。

Beginner
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.3333333333333335

Integer 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
2
i++ 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

位运算

OpMeaningExample
&按位与6 & 3 → 2
|按位或6 | 3 → 7
^按位异或(二元)/ 取反(一元)6 ^ 3 → 5,^6 → -7
&^按位清零:a &^ b = a & ^b6 &^ 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.

Friends & Partners