delete map[key] in go?

后端 未结 5 712
星月不相逢
星月不相逢 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:34

    Use make (chan int) instead of nil. The first value has to be the same type that your map holds.

    package main
    
    import "fmt"
    
    func main() {
    
        var sessions = map[string] chan int{}
        sessions["somekey"] = make(chan int)
    
        fmt.Printf ("%d\n", len(sessions)) // 1
    
        // Remove somekey's value from sessions
        delete(sessions, "somekey")
    
        fmt.Printf ("%d\n", len(sessions)) // 0
    }
    

    UPDATE: Corrected my answer.

提交回复
热议问题