Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "delete" a key from a map in Go (golang) using reflection

Tags:

go

I am trying to delete a key from a map using reflection, and I cannot find a way to do it. What am I missing? I have the below code (http://play.golang.org/p/7Et8mgmSKO):

package main

import (
    "fmt"
    "reflect"
)

func main() {
    m := map[string]bool{
        "a": true,
        "b": true,
    }

    delete(m, "a")
    fmt.Printf("DELETE: %v\n", m)

    m = map[string]bool{
        "a": true,
        "b": true,
    }

    m["a"] = false
    fmt.Printf("ASSIGN: %v\n", m)

    m = map[string]bool{
        "a": true,
        "b": true,
    }
    v := reflect.ValueOf(m)
    v.SetMapIndex(reflect.ValueOf("a"), reflect.Zero(reflect.TypeOf(m).Elem()))
    fmt.Printf("REFLECT: %v\n", m)
}

Which generates the output:

DELETE: map[b:true]
ASSIGN: map[a:false b:true]
REFLECT: map[a:false b:true]

As you can see, the reflection case seems to be identical to assigning a zero value, not deleting it. This seems to be contrary to the documentation for reflect.SetMapIndex() which says (http://golang.org/pkg/reflect/#Value.SetMapIndex):

If val is the zero Value, SetMapIndex deletes the key from the map.

For my application, I need to actually remove the key from the map. Any ideas?

like image 755
George Madrid Avatar asked Apr 29 '14 15:04

George Madrid


People also ask

How do you delete something from your map in Go?

The special syntax for deleting map entries is removed in Go version 1: Go 1 will remove the special map assignment and introduce a new built-in function, delete : delete(m, x) will delete the map entry retrieved by the expression m[x] . ...

How do I create a Golang map?

Go by Example: Maps Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt.


1 Answers

Rather than a reflect.Value that represents the zero value for the map's value type, SetMapIndex expects a zero value for reflect.Value itself in order to delete a key. So you instead want something like this:

v.SetMapIndex(reflect.ValueOf("a"), reflect.Value{})
like image 154
James Henstridge Avatar answered Nov 15 '22 07:11

James Henstridge