Reputation: 9185
How does one delete data from a map in Go? For example, having
m := map[string]string{ "key1":"val1", "key2":"val2" };
I want to make m drop the "key1" without copying the entire map by iterating over its keys (which could get big in some uses). Is it enough to assign a nil value to "key1", or will that still keep the key in the map structure with an assigned value of nil? That is, if I later iterate over the keys of the map, will "key1" appear?
Upvotes: 34
Views: 14850
Reputation: 166626
The built-in function
delete
removes the element with key k from a map m.delete(m, k) // remove element m[k] from map m
For example,
package main
import "fmt"
func main() {
m := map[string]string{"key1": "val1", "key2": "val2"}
fmt.Println(m)
delete(m, "key1")
fmt.Println(m)
}
Output:
map[key1:val1 key2:val2]
map[key2:val2]
Upvotes: 53