-1

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 ()
Pkzzz
  • 101
  • 1
  • 7
  • 3
    Look at the signature: `func()`. It receives no arguments and returns no arguments. You'll need to use a different method for passing the data, such as a `channel`. – Gavin Apr 29 '21 at 11:49
  • 2
    if the function signature does not have ouputs parameters then you are not allowed to return values. You wrote a function `func()`, it should be `func() Response`. Though, more generally, you dont return from an anonymous function executed asynchronously because the output values are lost. It is not possible to write `res := go func() Response { ... }()`. You have to write a mechanism to copy or share a pointer reference of that value to other routines. –  Apr 29 '21 at 11:51
  • related: [Catching return values from goroutines](https://stackoverflow.com/q/20945069/10197418) – FObersteiner Apr 29 '21 at 11:53

2 Answers2

4

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
}
XciD
  • 2,537
  • 14
  • 40
0

The function you provide to span a go routine has no return in its signature. Go routines cannot return data. Running goroutine (asynchronously) and fetch return value from function are essentially contradictory actions. Simply put, goroutine cannot know where to return the data. Hence it doesnot allow it.

You can do something like this:

var response Response

var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done()
    res, err := example(a, b)
    if err != nil {
        response = res
    }
}()
wg.Wait()

return response
advay rajhansa
  • 1,129
  • 9
  • 17