tags:

views:

157

answers:

3

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.

+3  A: 

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
Jurily
`sessions.go:6: cannot use 0 (type int) as type chan int`
Kinopiko
@Kinopiko: I don't think Jurily meant for the OP to use that code snippet. He just copied an example from the docs.
DoR
A: 

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.

DoR
`sessions.go:6: cannot use 0 (type int) as type chan int`
Kinopiko
Oops, forgot that I removed that too :P
DoR
`package main func main () {var sessions = map[string] chan int{};sessions["moo"] = make (chan int);}`
Kinopiko
The above compiles and runs on my version of Go.
Kinopiko
+1  A: 

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;
    }
}
Kinopiko
Looking up the value and reusing it must be cheaper: `sessions["moo"] = sessions["moo"], false;` (or is that wrong?)
kaizer.se
That crashes unless the key is present. I've added another solution based on your idea.
Kinopiko