【发布时间】:2020-08-19 10:02:53
【问题描述】:
type Tasks map[int]CustomValue
func (t *Tasks) Put(task MyTask) {
(*t)[len(*t)] = task
return len(*t) - 1
}
func (t *Tasks) Get(taskID int) interface{} {
defer func() { // Is this OK???
delete(*t, taskID)
}()
return (*t)[jobID].GetValue()
}
这是我的 Go 代码。基本上,我使用地图来存储一些“键值”。我有两个函数Put 和Get。
得到值后,我想从地图中删除元素。
我可以简单地使用延迟机制来做到这一点吗?不知道return后是否必须调用defer函数。
【问题讨论】:
-
如果你有多个 goroutines 使用这些函数,你需要一个互斥体来防止数据竞争。互斥锁解锁可以放在
defer。
标签: dictionary pointers go deferred