I have a function which can be called sequentially or concurrently in separate goroutine.
I want to ensure that function is executed completely before main goroutine finishes, so I am passing *sync.WaitGroup argument to the function. Now, at some places the function is to be called sequentially.
I can pass nil waitGroup to the function like this:
func my_func(wg *sync.WaitGroup){
if wg != nil{
defer wg.Done()
}
// do the task
}
func main(){
my_func(nil) // sequential call
wg := sync.WaitGroup{}
wg.Add(1)
go my_func(&wg) // concurrent call
wg.Wait()
}
Is there any better way to achieve this ?