Go 循环指针变化 [英] Go loop pointer changes

查看:75
本文介绍了Go 循环指针变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Go 中使用 for range 循环来遍历结构体.

I am using a for range loop in Go to iterate through a slice of structs.

在每个循环中,我是一个指向当前项目的指针,指向一个变量.

In each loop, I a pointer to the current item to a variable.

我很困惑为什么指针会在下一个循环中改变值.

I am confused why the pointer changes value in the next loop.

例如这段代码:

package main

import "fmt"

type t struct {
    val int
}

func main() {
    l := []t{{1}, {2}}
    var p *t
    for _, i := range l {
        fmt.Println("begin", p)
        p = &i
        fmt.Println("end", p)
    }
}

我希望生产:

begin <nil>
end &{1}
begin &{1}
end &{2}

但实际上是:

begin <nil>
end &{1}
begin &{2}
end &{2}

作为参考,在我的实际代码中,我在循环期间检查条件,并返回当前项和前一项.所以我试图保存一个指向它的指针,以便在下一次迭代中它也可以访问前一次.

For reference, in my actual code, I am checking for a condition during the loop, and returning the current item and previous one. So I am trying to save a pointer to it, so that in the next iteration it will have access to the previous as well.

推荐答案

问题是您获取的是循环/范围变量的地址,而不是切片中项目的地址.然而,你只是为自己做了很多不必要的工作.一方面,为什么不使用 i, v := range 或更好的 i, _ := 然后你可以做 i-1 获取上一项?其次,即使你想把它保存在一个指针中,仍然使用这个语法然后赋值 p = &l[i] 这样你就可以得到切片中项目的地址而不是循环/范围变量.

The problem is that you're taking the address of the loop/range variable and not the address of the item in slice. However, you're just making a lot of unnecessary work for yourself. For one, why don't you use the i, v := range or better yet i, _ := and then you can do i-1 to get the previous item? Secondly, even if you want it saved in a pointer, still use this syntax and then assign p = &l[i] so you have the address of the item in the slice rather than the address of the loop/range variable.

当使用索引显然更好时,人们太急于使用 for/each 样式构造......如果您希望每次迭代都使用 index-1,那么使用索引应该是您的首选方式.

People are way too eager to use for/each style constructs when it's obviously better to work with the index... If you want index-1 on every iteration, using the index should be your go to way of doing that.

这篇关于Go 循环指针变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆