Files
the-way-to-go_ZH_CN/eBook/07.3.md
Haigang Zhou 30ca13a369 7-8 章修改 (#842)
Co-authored-by: Joe Chen <jc@unknwon.io>
2022-05-10 13:53:30 +08:00

110 lines
2.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 7.3 For-range 结构
这种构建方法可以应用于数组和切片:
```go
for ix, value := range slice1 {
...
}
```
第一个返回值 `ix` 是数组或者切片的索引,第二个是在该索引位置的值;他们都是仅在 `for` 循环内部可见的局部变量。`value` 只是 `slice1` 某个索引位置的值的一个拷贝,不能用来修改 `slice1` 该索引位置的值。
示例 7.9 [slices_forrange.go](examples/chapter_7/slices_forrange.go)
```go
package main
import "fmt"
func main() {
var slice1 []int = make([]int, 4)
slice1[0] = 1
slice1[1] = 2
slice1[2] = 3
slice1[3] = 4
for ix, value := range slice1 {
fmt.Printf("Slice at %d is: %d\n", ix, value)
}
}
```
示例 7.10 [slices_forrange2.go](examples/chapter_7/slices_forrange2.go)
```go
package main
import "fmt"
func main() {
seasons := []string{"Spring", "Summer", "Autumn", "Winter"}
for ix, season := range seasons {
fmt.Printf("Season %d is: %s\n", ix, season)
}
var season string
for _, season = range seasons {
fmt.Printf("%s\n", season)
}
}
```
slices_forrange2.go 给出了一个关于字符串的例子, `_` 可以用于忽略索引。
如果你只需要索引,你可以忽略第二个变量,例如:
```go
for ix := range seasons {
fmt.Printf("%d", ix)
}
// Output: 0 1 2 3
```
如果你需要修改 `seasons[ix]` 的值可以使用这个版本。
**多维切片下的 for-range**
通过计算行数和矩阵值可以很方便的写出如(参考[第 7.1.3 节](07.1.md))的 `for` 循环来,例如(参考[第 7.5 节](07.5.md)的例子 [multidim_array.go](exercises/chapter_7/multidim_array.go)
```go
for row := range screen {
for column := range screen[row] {
screen[row][column] = 1
}
}
```
**问题 7.5** 假设我们有如下数组:`items := [...]int{10, 20, 30, 40, 50}`
a) 如果我们写了如下的 `for` 循环,那么执行完 `for` 循环后的 `items` 的值是多少?如果你不确定的话可以测试一下:)
```go
for _, item := range items {
item *= 2
}
```
b) 如果 a) 无法正常工作,写一个 `for` 循环让值可以变成自身的两倍。
**问题 7.6** 通过使用省略号操作符 `...` 来实现累加方法。
**练习 7.7** [sum_array.go](exercises/chapter_7/sum_array.go)
a) 写一个 `Sum()` 函数,传入参数为一个 `float32` 数组成的数组 `arrF`,返回该数组的所有数字和。
如果把数组修改为切片的话代码要做怎样的修改?如果用切片形式方法实现不同长度数组的的和呢?
b) 写一个 `SumAndAverage()` 方法,返回两个 int 和 `float32` 类型的未命名变量的和与平均值。
**练习 7.8** [min_max.go](exercises/chapter_7/min_max.go)
写一个 `minSlice()` 方法,传入一个 `int` 的切片并且返回最小值,再写一个 `maxSlice()` 方法返回最大值。
## 链接
- [目录](directory.md)
- 上一节:[切片](07.2.md)
- 下一节:[切片重组 (reslice)](07.4.md)