I have a map:
var sessions = map[string] chan int{}
How do I delete sessions[key]
? I tried:
sessions[key] = nil,
delete(sessions, "anykey")
These days, nothing will crash.
From Effective Go:
To delete a map entry, use the delete built-in function, whose arguments are the map and the key to be deleted. It's safe to do this even if the key is already absent from the map.
delete(timeZone, "PDT") // Now on Standard Time
In the old language, to delete the entry with key k
from the map represented by m
, one wrote the statement,
m[k] = value, false
This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.
In Go 1, that syntax has gone; instead there is a new built-in function, delete
. The call
delete(m, k)
will delete the map entry retrieved by the expression m[k]
. There is no return value. Deleting a non-existent entry is a no-op.
Updating: Running go fix
will convert expressions of the form m[k] = value, false
into delete(m, k)
when it is clear that the ignored value can be safely discarded from the program and false
refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.
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");
}
}
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.