Search code examples
gogoroutine

goroutine error: too many arguments to return


I have a function works before using goroutine:

res, err := example(a , b)
if err != nil {
 return Response{
   ErrCode: 1,
   ErrMsg:"error",
 }
}

Response is a struct defined error info. When I use goroutine:

var wg sync.WaitGroup()
wg.Add(1)
go func(){
   defer wg.Done()
   res, err := example(a , b)
   if err != nil {
      return Response{
         ErrCode: 1,
         ErrMsg:"error",
    }
}()
wg.Wait()

Then I got

too many arguments to return
    have (Response)
    want ()

Solution

  • You need to use channel to achieve what you want:

    func main() {
        c := make(chan Response)
        go func() {
            res, err := example(a , b)
            if err != nil {
                c <- Response{
                    ErrCode: 1,
                    ErrMsg:"error",
                }
            }
        }()
        value := <-c
    }