Maps

A map type allows you to get the type of both value and key, using the Key and Elem methods:

func main() {
maps := []interface{}{
make(map[string]struct{}),
make(map[int]rune),
make(map[float64][]byte),
make(map[int32]chan bool),
make(map[[2]string]interface{}),
}
for _, m := range maps {
t := reflect.TypeOf(m)
fmt.Printf("%s k:%-10s v:%-10s ", m, t.Key(), t.Elem())
}
}

A full example is available here: https://play.golang.org/p/j__1jtgy-56.

The values can be accessed in all the ways that a map can be accessed normally:

  • By getting a value using a key
  • By ranging over keys
  • By ranging over values

Let's see how it works in a practical example:

func main() {
m := map[string]int64{
"a": 10,
"b": 20,
"c": 100,
"d": 42,
}

v := reflect.ValueOf(m)

// access one field
fmt.Println("a", v.MapIndex(reflect.ValueOf("a")))
fmt.Println()

// range keys
for _, k := range v.MapKeys() {
fmt.Println(k, v.MapIndex(k))
}
fmt.Println()

// range keys and values
i := v.MapRange()
for i.Next() {
fmt.Println(i.Key(), i.Value())
}
}

Note that we don't need to pass a pointer to the map to make it addressable, because maps are already pointers.

Each method is pretty straightforward and depends on the type of access you need to the map. Setting values is also possible, and should always be possible because maps are passed by reference. The following snippet shows a practical example:

func main() {
m := map[string]int64{}
v := reflect.ValueOf(m)

// setting one field
v.SetMapIndex(reflect.ValueOf("key"), reflect.ValueOf(int64(1000)))

fmt.Println(m)
}

A full example is available here: https://play.golang.org/p/JxK_8VPoWU0.

It is also possible to use this method to unset a variable, like we do when calling the delete function using the zero value of reflect.Value as a second argument:

func main() {
m := map[string]int64{"a": 10}
fmt.Println(m, len(m))

v := reflect.ValueOf(m)

// deleting field
v.SetMapIndex(reflect.ValueOf("a"), reflect.Value{})

fmt.Println(m, len(m))
}

A full example is available here: https://play.golang.org/p/4bPqfmaKzTC.

The output will have one less field as it gets deleted because the length of the map decreases after SetMapIndex.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181