Why do keys and values from a map share the same memory address?


I notice that when iterating across keys and values in a map, they keys and values all share the same memory address. You can see that here:

package main

import "fmt"

func main() {
    myMap := map[string]string{
        "hello": "world",
        "how":   "are",
        "you":   "today?",
    for key, value := range myMap {
        fmt.Printf("Key: %p %v\n", &key, key)
        fmt.Printf("Value: %p %v\n", &value, value)

… which outputs …

Key: 0xc00009e210 hello
Value: 0xc00009e220 world
Key: 0xc00009e210 how
Value: 0xc00009e220 are
Key: 0xc00009e210 you
Value: 0xc00009e220 today?

Why is that?


You are not taking the address of the values in the map. Actually, map elements are not addressable in Go. You are taking the addresses of the local loop variables, called "key" and "value". Those don’t change across each loop iteration, because there is no reason for them to (they are re-used).


Why does Go forbid taking the address of (&) map member, yet allows (&) slice element?

Answered By – Hymns For Disco

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.