dongshi1207 2018-03-19 03:21
浏览 1595
已采纳

如何清理sync.map?

I can't have access to map inside Range loop method. I just want an equivalente method of normal map apply in 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条回答 默认 最新

  • douhutongvm382381 2018-03-19 03:49
    关注

    For example,

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

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

    Or

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

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

    Or

    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

    Or

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题