gpt4 book ai didi

go - 如何清理 sync.map?

转载 作者:IT王子 更新时间:2023-10-29 01:27:04 25 4
gpt4 key购买 nike

我无法访问 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
}

最佳答案

例如,

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

Playground :https://play.golang.org/p/PTASV3sEIxJ

或者

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

Playground :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)
}

Playground :https://play.golang.org/p/lCBkUv6GJIO

或者

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

Playground :https://play.golang.org/p/s-KYelDxqFB

关于go - 如何清理 sync.map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com