Go:获取 Map 成员的地址

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

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)
}

huangapple
  • 本文由 发表于 2014年3月21日 02:02:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/22541473.html
匿名

发表评论

匿名网友

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

确定