要删除地图[关键字]吗? [英] delete map[key] in go?

查看:52
本文介绍了要删除地图[关键字]吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张地图:

var sessions =  map[string] chan int{}

如何删除个会话[密钥] ?我尝试过:

sessions[key] = nil,false;

那没用。

更新(2011年11月):

Update (November 2011):

用于删除地图条目的特殊语法已在转到版本1

The special syntax for deleting map entries is removed in Go version 1:


Go 1将删除特殊的地图分配,并引入一个新的内置函数删除 delete(m,x)将删除表达式 m [x] 。 ...

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]. ...


推荐答案

奇怪的是,

package main

func main () {
    var sessions = map[string] chan int{};
    delete(sessions, "moo");
}

似乎可以工作。

另一种方法是检查是否存在并使用值本身:

Another way is to check for existence and use the value itself:

package main

func main () {
    var sessions = map[string] chan int{};
    sessions["moo"] = make (chan int);
    _, ok := sessions["moo"];
    if ok {
        delete(sessions, "moo");
    }
}

这篇关于要删除地图[关键字]吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆