I want to concurrently parse files with the parseFile()
function and assign its return values to the fields of a struct with type fileInfo
which is located in a slice of structs files []fileInfo
.
The files
struct is prepopulated with fileInfo
elements and I want to update the fields A,B
of each fileInfo
element in the slice.
Question: Is my code idiomatic for Go or should it be solved differently?
I am using sync.Mutex
for now to lock the struct in the slice but I wonder if there is a better solution for this task or if the code is even correct and does not just work by chance.
type fileInfo struct {
A []string
B string
Path string
UpdateMutex sync.Mutex
}
func parseFile(filePath string) ([]string, string, error) {
var a []string
var b string
var err error
//do some parsing
//...
return a, b, err
}
func main() {
var files []fileInfo
//pre-populate fileInfo
wg := new(sync.WaitGroup)
for i, _ := range files {
wg.Add(1)
go func(pFile *fileInfo) {
var err error
defer wg.Done()
pFile.UpdateMutex.Lock()
pFile.A, pFile.B, err = parseFile(pFile.Path)
pFile.UpdateMutex.Unlock()
if err != nil {
fmt.Println(err)
}
}(&files[i])
}
//more work
//...
wg.Wait()
//continue
}
I thought about using channels but I can't quite wrap my head around how one can update a specific files[i].A
using a channel.