循环语句是一种常用的控制结构,在 Go 语言中,除了 for 关键字以外,还有一个 range 关键字,可以使用 for-range
但是在使用 for-range 循环迭代数组和切片的时候,是很容易出错的,甚至很多老司机一不小心都会在这里翻车。
具体是怎么翻的呢?我们接着看。
先来看两段很有意思的代码:
如果我们在遍历数组的同时向数组中添加元素,能否得到一个永远都不会停止的循环呢?
比如下面这段代码:
func main() { arr := []int{ 1, 2, 3} for _, v := range arr { arr = append(arr, v) } fmt.Println(arr)}
程序输出:
$ go run main.go1 2 3 1 2 3
上述代码的输出意味着循环只遍历了原始切片中的三个元素,我们在遍历切片时追加的元素并没有增加循环的执行次数,所以循环最终还是停了下来。
第二个例子是使用 Go 语言经常会犯的一个错误。
当我们在遍历一个数组时,如果获取 range 返回变量的地址并保存到另一个数组或者哈希时,会遇到令人困惑的现象:
func main() { arr := []int{ 1, 2, 3} newArr := []*int{ } for _, v := range arr { newArr = append(newArr, &v) } for _, v := range newArr { fmt.Println(*v) }}
程序输出:
$ go run main.go3 3 3
上述代码并没有输出 1 2 3,而是输出 3 3 3。
正确的做法应该是使用 &arr[i] 替代 &v,像这种编程中的细节是很容易出错的。
具体原因也并不复杂,一句话就能解释。
对于数组、切片或字符串,每次迭代,for-range 语句都会将原始值的副本传递给迭代变量,而非原始值本身。
口说无凭,具体是不是这样,还得靠源码说话。
Go 编译器会将 for-range 语句转换成类似 C 语言的三段式循环结构,就像这样:
// Arrange to do a loop appropriate for the type. We will produce// for INIT ; COND ; POST { // ITER_INIT// INDEX = INDEX_TEMP// VALUE = VALUE_TEMP // If there is a value// original statements// }
迭代数组时,是这样:
// The loop we generate:// len_temp := len(range)// range_temp := range// for index_temp = 0; index_temp < len_temp; index_temp++ { // value_temp = range_temp[index_temp]// index = index_temp// value = value_temp// original body// }
切片:
// for_temp := range// len_temp := len(for_temp)// for index_temp = 0; index_temp < len_temp; index_temp++ { // value_temp = for_temp[index_temp]// index = index_temp// value = value_temp// original body// }
从上面的代码片段,可以总结两点:
以上就是本文的全部内容,如果觉得还不错的话欢迎点赞,转发和关注,感谢支持。
(责任编辑:百科)
深圳三部门:持续深化融资租赁、商业保理行业清理规范 加强部门协同