Go delete map


清空 map

import (
    "fmt"
    "time"
)

func main() {
    testMap := make(map[string]string)
    testMap["k"] = "v"
    fmt.Println(testMap)
    time.Sleep(time.Second * 2)
    for key, value := range testMap {
        fmt.Println(value)
        delete(testMap, key)
    }
    fmt.Println(testMap)
}

原理

func mapdelete(t *maptype, h *hmap, key unsafe.Pointer) {
    for ; b != nil; b = b.overflow(t) {
        for i := uintptr(0); i < bucketCnt; i++ {
            b.tophash[i] = empty
            h.count--
    }
    }
}
分享:

评论