如何清理sync.map?

时间:2018-03-19 03:21:12

标签: go

我无法访问Range循环方法中的map。我只想在sync.map中使用等效的法线贴图方法 https://play.golang.org/p/515_MFqSvCm

package main

import (
    "sync"
)

type list struct {
    code string
    fruit
}

type fruit struct {
    name     string
    quantity int
}

func main() {
    lists := []list{list{"asd", fruit{"Apple", 5}}, list{"ajsnd", fruit{"Apple", 10}}, list{"ajsdbh", fruit{"Peach", 15}}}
    map1 := make(map[string]fruit)
    var map2 sync.Map
    for _, e := range lists {
        map1[e.code] = e.fruit
        map2.Store(e.code, e.fruit)
    }

    //erase map
    for k, _ := range map1 {
        delete(map1, k)
    }

    //can´t pass map as argument,so I can´t delete it´s values
    map2.Range(aux)
}

func aux(key interface{}, value interface{}) bool {
    map2.Delete(key) //doesn´t work
    return true
}

1 个答案:

答案 0 :(得分:3)

例如,

//erase map
map2.Range(func(key interface{}, value interface{}) bool {
    map2.Delete(key)
    return true
})

游乐场:https://play.golang.org/p/PTASV3sEIxJ

//erase map
delete2 := func(key interface{}, value interface{}) bool {
    map2.Delete(key)
    return true
}
map2.Range(delete2)

游乐场:https://play.golang.org/p/jd8dl71ee94

func eraseSyncMap(m *sync.Map) {
    m.Range(func(key interface{}, value interface{}) bool {
        m.Delete(key)
        return true
    })
}

func main() {
    // . . .

    //erase map
    eraseSyncMap(&map2)
}

游乐场:https://play.golang.org/p/lCBkUv6GJIO

//erase map: A zero sync.Map is empty and ready for use.
map2 = sync.Map{}

游乐场:https://play.golang.org/p/s-KYelDxqFB