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

huangapple go评论78阅读模式
英文:

How can I get a struct pointer from a slice in golang

问题

这是代码:

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` 是最后一个元素的指针值。

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

如何获取正确的指针值?

<details>
<summary>英文:</summary>

Here is the code:

    package main

    import (
	    &quot;fmt&quot;
    )

    type demo struct {
	     name string
    }

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

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

The result:

    {str1}==++++++++++++++0x20818a220
    
    {str2}==++++++++++++++0x20818a220
    
    {str3}==++++++++++++++0x20818a220

`0x20818a220` is the last element&#39;s pointer value.

Why are all the pointer values ​​the same?

How can I get those right pointer values?


</details>


# 答案1
**得分**: 6

你不是在引用切片的元素,而是引用了本地的`value`变量:

```go
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
英文:

You're not referring to the elements of the slice but the local value variable:

fmt.Printf(&quot;\n%v==++++++++++++++%p\n&quot;, value, &amp;value)

Hence all the pointer values will be the same (the address of local variable value). If you want pointers to the elements of the slice, then take the address of the appropriate element:

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

This will produce the following output, all pointers are different:

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

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

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

huangapple
  • 本文由 发表于 2015年2月18日 15:48:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/28578526.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定