delete map[key] in go?

后端 未结 5 804
星月不相逢
星月不相逢 2021-01-30 04:46

I have a map:

var sessions =  map[string] chan int{}

How do I delete sessions[key]? I tried:

sessions[key] = nil,         


        
5条回答
  •  佛祖请我去吃肉
    2021-01-30 05:17

    Strangely enough,

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

    seems to work. This seems a poor use of resources though!

    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");
        }
    }
    

提交回复
热议问题