go - How to explain golang slice range's phenomenon -


this question has answer here:

type student struct {     name string     age  int }  func main() {     m := make(map[string]*student)     s := []student{         {name: "allen", age: 24},         {name: "tom", age: 23},     }      _, stu := range s {         m[stu.name] = &stu     }     fmt.println(m)     key, value := range m {         fmt.println(key, value)     } } 

result:

map[allen:0xc42006a0c0 tom:0xc42006a0c0]

allen &{tom 23}

tom &{tom 23}

how explain slice's phenomenon, in opinion, stu should address of every member of s, results, s has same address.

the application taking address of local variable stu. change code take address of slice element:

for := range s {     m[s[i].name] = &s[i] } 

https://play.golang.org/p/0izo4ggpv7


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -