gopl-zh.github.com/ch2/ch2-04.md

32 lines
1009 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

## 2.4. 賦值
使用賦值語句可以更新一個變量的值,最簡單的賦值語句是將要被賦值的變量放在=的左邊,新值的表達式放在=的右邊。
```Go
x = 1 // 命令變量的賦值
*p = true // 通過指針間接賦值
person.name = "bob" // 結構體字段賦值
count[x] = count[x] * scale // 數組、slice或map的元素賦值
```
特定的二元算術運算符和賦值語句的複合操作有一個簡潔形式,例如上面最後的語句可以重寫爲:
```Go
count[x] *= scale
```
這樣可以省去對變量表達式的重複計算。
數值變量也可以支持`++`遞增和`--`遞減語句(譯註:自增和自減是語句,而不是表達式,因此`x = i++`之類的表達式是錯誤的):
```Go
v := 1
v++ // 等價方式 v = v + 1v 變成 2
v-- // 等價方式 v = v - 1v 變成 1
```
{% include "./ch2-04-1.md" %}
{% include "./ch2-04-2.md" %}