[英]How can I get a struct pointer from a slice in golang
Here is the code: 这是代码:
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
}
}
The result: 结果:
{str1}==++++++++++++++0x20818a220
{str2}==++++++++++++++0x20818a220
{str3}==++++++++++++++0x20818a220
0x20818a220
is the last element's pointer value. 0x20818a220
是最后一个元素的指针值。
Why are all the pointer values the same? 为什么所有的指针值都一样?
How can I get those right pointer values? 如何获得那些正确的指针值?
You're not referring to the elements of the slice but the local value
variable: 您不是在指切片的元素,而是局部value
变量:
fmt.Printf("\n%v==++++++++++++++%p\n", value, &value)
Hence all the pointer values will be the same (the address of local variable value
). 因此,所有指针值都将是相同的(局部变量value
的地址)。 If you want pointers to the elements of the slice, then take the address of the appropriate element: 如果您想要指向切片元素的指针,请获取适当元素的地址:
fmt.Printf("\n%v==++++++++++++++%p\n", demo_slice[index], &demo_slice[index])
This will produce the following output, all pointers are different: 这将产生以下输出,所有指针都不同:
{str1}==++++++++++++++0x104342e0
{str2}==++++++++++++++0x104342e8
{str3}==++++++++++++++0x104342f0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.