我已经使用 Go 一段时间了。我想知道是否有任何短格式代码可以从goroutine获取返回值。
x := 3
ch := make(chan int)
go func(xIn int) (xOut int) {
xOut = x + 1
ch <- xOut
return xOut
}(x)
nextX := <-ch
fmt.Println(x, nextX)
建议的简写形式:
x := 3
nextX := go func(xIn int) (xOut int) {
xOut = x + 1
return xOut
}(x)
fmt.Println(x, nextX)
重点:
问题不在于如何做到这一点,而在于为什么go-complier没有提供这样的功能。
我们假设存在一些返回类型T
的函数f()
。
您希望捕获f()
的返回值。 显然,我们可以通过以下方式做到这一点:
x := f()
如果:
x := go f()
等待f()
return
一些值分配给x
,这两个调用之间有什么区别?
(如果:
x := go f()
不等待f()
return
值,当您尝试访问变量x
时会发生什么?
如果你想写:
x := 3
nextX := func(xIn int) (xOut int) {
xOut = x + 1
return xOut
}(x)
fmt.Println(x, nextX)
你可以在今天的 Go 中这样做。 (在Go Playground上尝试一下。 另外,我怀疑您希望内部函数使用其xIn
变量,而不是闭包捕获的x
变量,但无论哪种方式,效果都是一样的。