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

如何清理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

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度