英文:
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论