我有一个带有开关的 goroutine,它想要将一个接口附加到一个结构体,但是当运行它时,我没有收到错误,但它没有附加任何响应,你如何在 Go 中编写它以使其并发安全?
这是我的代码:
var wg sync.WaitGroup
for _, v := range inputParameters.Entities {
go func(v domain.Entity) {
wg.Add(1)
defer wg.Done()
var f func(
v domain.Entity,
result *domain.Resoponse,
)(interface{}, Error) // Signature of all Get methods
switch v.Name {
case "process1":
f = 1Processor{}.Get
case "process2":
f = 2Processor{}.Get
case "process3":
f = 3Processor{}.Get
default:
return
}
res, err := f(v, result)
if err != nil {
mapError.Error = append(mapError.Error, err)
} else {
result.Mu.Lock()
defer result.Mu.Unlock()
result.Entities = append(result.Entities, res)
}
}(v)
}
wg.Wait()
return result, mapError
作为参考,这里是Response类型:
type Resoponse struct {
Mu sync.Mutex
Entities []interface{}
}
小唯快跑啊
相关分类