英文:
Go: Taking the address of Map Members
问题
有人能解释一下为什么r包含了两个相同地址的条目吗?
r := make([]*Result, len(m))
i := 0
for _, res := range m {
fmt.Println("index, result:", i, *&res)
r[i] = &res
i++
}
fmt.Println(r)
结果如下:
index, result: 0 {[] map[0:1 1:1] {port=6379}}
index, result: 1 {[] map[0:1 1:1] {port=6380}}
[0xc21010d6c0 0xc21010d6c0]
英文:
Can someone explain why r contains two entires of the same address?
r := make([]*Result, len(m))
i := 0
for _, res := range m {
fmt.Println("index, result:", i, *&res)
r[i] = &res
i++
}
fmt.Println(r)
Results in:
index, result: 0 {[] map[0:1 1:1] {port=6379}}
index, result: 1 {[] map[0:1 1:1] {port=6380}}
[0xc21010d6c0 0xc21010d6c0]
答案1
得分: 1
res
的值在每次循环迭代时给出。
具有相同地址只意味着内存中的那个位置被重用。
英文:
The value of res
is given at each iteration of the loop.
The fact you have the same address only means that point in memory is reused.
答案2
得分: 1
使用*Result
作为映射值。例如,
package main
import "fmt"
type Result struct{}
func main() {
m := make(map[string]*Result)
r := make([]*Result, 0, len(m))
for _, res := range m {
fmt.Println("index, result:", len(r), *res)
r = append(r, res)
}
fmt.Println(r)
}
英文:
Use *Result
as the map value. For example,
package main
import "fmt"
type Result struct{}
func main() {
m := make(map[string]*Result)
r := make([]*Result, 0, len(m))
for _, res := range m {
fmt.Println("index, result:", len(r), *res)
r = append(r, res)
}
fmt.Println(r)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论