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

31 lines
1002 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" %}