如何从golang中的切片获取结构指针

时间:2015-02-18 07:48:37

标签: pointers go struct slice

以下是代码:

package main

import (
    "fmt"
)

type demo struct {
     name string
}

func main() {
     demo_slice := make([]demo, 3)
     demo_slice[0] = demo{"str1"}
     demo_slice[1] = demo{"str2"}
     demo_slice[2] = demo{"str3"}

     point_demo_slice := make([]*demo, 3)
     for index, value := range demo_slice {
          fmt.Printf("\n%v==++++++++++++++%p\n", value, &value)
          point_demo_slice[index] = &value
     }
}

结果:

{str1}==++++++++++++++0x20818a220

{str2}==++++++++++++++0x20818a220

{str3}==++++++++++++++0x20818a220

0x20818a220是最后一个元素的指针值。

为什么所有指针值都相同?

如何获得正确的指针值?

1 个答案:

答案 0 :(得分:5)

您并未提及切片的元素,而是指本地value变量:

fmt.Printf("\n%v==++++++++++++++%p\n", value, &value)

因此所有指针值都是相同的(局部变量value的地址)。如果需要指向切片元素的指针,请获取相应元素的地址:

fmt.Printf("\n%v==++++++++++++++%p\n", demo_slice[index], &demo_slice[index])

这将产生以下输出,所有指针都不同:

{str1}==++++++++++++++0x104342e0

{str2}==++++++++++++++0x104342e8

{str3}==++++++++++++++0x104342f0