Files
the-way-to-go_ZH_CN/eBook/07.3.md

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