Kyle Brandt
Kyle Brandt

Reputation: 28457

Go: Taking the address of Map Members

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]

Upvotes: 0

Views: 175

Answers (2)

peterSO
peterSO

Reputation: 166885

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

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382454

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.

Upvotes: 1

Related Questions