地图 – 删除数据

huangapple go评论84阅读模式
英文:

maps - deleting data

问题

如何在Go中从map中删除数据?例如,有以下map:

m := map[string]string{ "key1":"val1", "key2":"val2" };

我想让m删除"key1",而不是通过迭代其键(在某些情况下可能很大)来复制整个map。将nil值分配给"key1"是否足够,或者它仍然会保留具有nil值的键在map结构中?也就是说,如果我稍后迭代map的键,"key1"会出现吗?

英文:

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?

答案1

得分: 53

> 删除map元素
>
> 内置函数delete从map m中删除具有键k的元素。
>
> delete(m, k) // 从map m中删除元素m[k]

例如,

package main

import "fmt"

func main() {
	m := map[string]string{"key1": "val1", "key2": "val2"}
	fmt.Println(m)
	delete(m, "key1")
	fmt.Println(m)
}

输出:

map[key1:val1 key2:val2]
map[key2:val2]
英文:

> Deletion of map elements
>
> 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]

huangapple
  • 本文由 发表于 2012年2月11日 03:22:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/9233564.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定