i have a map:
var sessions = map[string] chan int{}
How do i delete sessions[key] ?
tried:
sessions[key] = nil,false;
That did'nt work.
i have a map:
var sessions = map[string] chan int{}
How do i delete sessions[key] ?
tried:
sessions[key] = nil,false;
That did'nt work.
From Effective Go:
To delete a map entry, turn the multiple assignment around by placing an extra boolean on the right; if the boolean is false, the entry is deleted. It's safe to do this even if the key is already absent from the map.
timeZone["PDT"] = 0, false; // Now on Standard Time
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
sessions["somekey"] = make(chan int), false;
fmt.Printf ("%d\n", len(sessions)); // 0
}
UPDATE: Corrected my answer.
Strangely enough,
package main
func main () {
var sessions = map[string] chan int{};
sessions["moo"] = make (chan int), false;
}
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 {
sessions["moo"] = sessions["moo"], false;
}
}