是否可以让函数funcWithNonChanResult具有以下接口:
func funcWithNonChanResult() int {
如果我希望它funcWithChanResult在接口中使用函数:
func funcWithChanResult() chan int {
换句话说,我可以以某种方式转换chan int为int? 或者我必须chan int在所有使用的函数中都有结果类型funcWithChanResult?
目前,我尝试了这些方法:
result = funcWithChanResult()
// cannot use funcWithChanResult() (type chan int) as type int in assignment
result <- funcWithChanResult()
// invalid operation: result <- funcWithChanResult() (send to non-chan type int)
完整代码:
package main
import (
"fmt"
"time"
)
func getIntSlowly() int {
time.Sleep(time.Millisecond * 500)
return 123
}
func funcWithChanResult() chan int {
chanint := make(chan int)
go func() {
chanint <- getIntSlowly()
}()
return chanint
}
func funcWithNonChanResult() int {
var result int
result = funcWithChanResult()
// result <- funcWithChanResult()
return result
}
func main() {
fmt.Println("Received first int:", <-funcWithChanResult())
fmt.Println("Received second int:", funcWithNonChanResult())
}
Helenr
相关分类