delete map[key] in go?

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

    Copied from Go 1 release notes

    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.

提交回复
热议问题