Golang Reusing Memory Address Copying from slice?

前端 未结 2 1499
梦毁少年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 10:50

    In your first (non working) example item is the loop variable. Its address is not changing, only its value. That's why you get the same address in output idx times.

    Run this code to see the mechanics in action;

    func main() {
    
        coll := []int{5, 10, 15}
    
        for i, v := range coll {
           fmt.Printf("This one is always the same; %v\n", &v)
           fmt.Println("This one is 4 bytes larger each iteration; %v\n", &coll[i])
        }
    }
    

提交回复
热议问题