从goroutine捕获返回值

从goroutine捕获返回值

问题描述:

下面的代码给出了编译错误,提示意外的运行:

The below code gives compilation error saying 'unexpected go':

x := go doSomething(arg)

func doSomething(arg int) int{
    ...
    return my_int_value
}

我知道,如果正常调用该函数,则无需使用goroutine即可获取返回值。或者我可以使用通道等。

I know, I can fetch the return value if call the function normally, without using goroutine. Or I can use channels etc.

我的问题是为什么不能从goroutine中获取像这样的返回值。

My question is why is it not possible to fetch a return value like this from a goroutine.

严格的答案是您可以做到这一点。这可能不是一个好主意。下面的代码可以做到这一点:

The strict answer is that you can do that. It's just probably not a good idea. Here's code that would do that:

var x int
go func() {
    x = doSomething()
}()

这将产生一个新的goroutine,该例程将计算 doSomething(),然后将结果分配给 x 。问题是:如何使用原始goroutine中的 x ?您可能要确保已完成生成的goroutine的处理,以免出现争用情况。但是,如果要执行此操作,则需要一种与goroutine进行通信的方法,并且如果可以执行此操作,为什么不使用它来将值发送回去呢?

This will spawn off a new goroutine which will calculate doSomething() and then assign the result to x. The problem is: how are you going to use x from the original goroutine? You probably want to make sure the spawned goroutine is done with it so that you don't have a race condition. But if you want to do that, you'll need a way to communicate with the goroutine, and if you've got a way to do that, why not just use it to send the value back?