Golang Reusing Memory Address Copying from slice?

前端 未结 2 1498
梦毁少年i
梦毁少年i 2021-01-13 10:37

I was hitting an issue in a project I\'m working on. I found a way around it, but I wasn\'t sure why my solution worked. I\'m hoping that someone more experience with how

2条回答
  •  春和景丽
    2021-01-13 11:04

    There is just one item variable for the entire loop, which is assigned the corresponding value during each iteration of the loop. You do not get a new item variable in each iteration. So you are just repeatedly taking the address of the same variable, which will of course be the same.

    On the other hand, if you declared a local variable inside the loop, it will be a new variable in each iteration, and the addresses will be different:

    for idx, item := range *coll {
        temp := item
        output[idx] = &temp
    }
    

提交回复
热议问题