Pass arguments to errgroup within a loop

Hi,

Is there a way to pass an argument to errgroup routines just like we do in classic go routines?

Thanks

classic way

for i := 1; i < 5; i++ {
  id := i
  go func(id int) {
    if id == 3 {
      return error ....
    }
    // carry on running
  }(id)
}

errgroup way

var eg errgroup.Group

for i := 1; i < 5; i++ {
  id := i
  eg.Go(func() error {
    if id == 3 { // How do I get the id here?
      return error ....
    }
    // carry on running
  })
}

Based on the package source code and a handful of packages I found on godoc.org that use the errgroup package, the answer seems to be that you cannot pass explicit function parameters to errgroup.(*Group).Go. You have to use a closure like you already have in your second example.

Note that you don’t need to make an interior variable and pass in the function argument, either will do… So you can write this as

for i := 1; i < 5; i++ {
  id := i // this variable is part of the closure and it is remade each time round the look
  go func() {
    if id == 3 {
      return error ....
    }
    // carry on running
  }()
}

Which leads on the the errgroup solution (which is identical to what you’ve already written)

var eg errgroup.Group

for i := 1; i < 5; i++ {
  id := i
  eg.Go(func() error {
    if id == 3 { // This id is part of the closed over variables
      return error ....
    }
    // carry on running
  })
}

I thought it was necessary. Hence the reason asked this question. Obviously learned something else now. Thanks.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.