Go 支援下列算術運算子:
| 運算子 | 範例 |
|---|---|
+ |
4 + 6 == 10 |
- |
15 - 10 == 5 |
* |
2 * 3 == 6 |
/ |
13 / 3 == 4 |
% |
13 % 3 == 1 |
整數除法會捨去餘數(例如5 / 2 == 2)。
+運算子也可以用來串接字串:"foo" + "bar" == "foobar"。
Go 不允許在不同數值型別之間進行算術運算:
x := 42
n := 2.0
value := n * x // invalid operation: n * x (mismatched types float64 and int)
運算元必須是相同的型別,有時需要明確轉換:
x := float64(42)
n := 2.0
value := n * x
每個運算子都有簡寫賦值的形式,可以就地更新變數:
a := 1
a += 2 // same as a = a + 2 == 3
b := 2
b -= 2 // same as b = b - 2 == 0
c := 4
c *= 2 // same as c = c * 2 == 8
d := 8
d /= 2 // same as d = d / 2 == 4
e := 16
e %= 2 // same as e = e % 2 == 0
當置於變數之後時,遞增(++)與遞減(--)敘述會將變數儲存的數值增加或減少 1。
將它們放在變數之前會造成語法錯誤。
a := 10
a++ // same as a += 1, a == 11
b := 10
b-- // same as b -= 1, b == 9
由於它們是敘述,因此不會回傳值。