What is best way to pass context.Context
to closure to be executed in a separate goroutine?
Since I'm not mutating context.Context
inside the closure, I assume both options are valid. 2nd option can save me tiny bit of memory by not copying the interface.
1) pass as an argument
func run(ctx context.Context) {
for i := 0; i <= 5; i++ {
go func(id int, ictx context.Context) {
for {
select {
case <- ictx.Done():
return
default:
// do something
}
}
}(i, ctx)
}
}
2) expose outer context variable
func run(ctx context.Context) {
for i := 0; i <= 5; i++ {
go func(id int) {
for {
select {
case <- ctx.Done():
return
default:
// do something
}
}
}(i)
}
}