bradleyjkemp / memviz

Visualize your Go data structures using graphviz
MIT License
1.3k stars 51 forks source link

Map/Slice aliasing causes copies #10

Open bradleyjkemp opened 6 years ago

bradleyjkemp commented 6 years ago

The "address" of a map reflect.Value is actually the address of the struct field so although maps are reference types they get treated as if they have been copied if two e.g. structs reference the same map. Not sure we can actually solve this

package main

import (
    "fmt"
    "reflect"
)

type container struct {
    links map[string]string
}

func main() {

    test := &container{
        map[string]string{"hello":"world"},
    }

    copied := &container{}
    copied.links = test.links

        // here UnsafeAddr() (which we use for unique ids) are different
    fmt.Println(reflect.ValueOf(test).Elem().Field(0).UnsafeAddr(), reflect.ValueOf(copied).Elem().Field(0).UnsafeAddr())
}