英文:
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 (
"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.
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("\n%v==++++++++++++++%p\n", value, &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("\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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论