【发布时间】:2015-08-31 20:41:32
【问题描述】:
是否可以让函数funcWithNonChanResult有如下接口:
func funcWithNonChanResult() int {
如果我想让它在接口上使用函数funcWithChanResult:
func funcWithChanResult() chan int {
换句话说,我可以以某种方式将chan int 转换为int 吗?或者我必须在使用funcWithChanResult的所有函数中都有chan int结果类型?
目前,我尝试了以下方法:
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())
}
【问题讨论】:
-
Go 是静态类型的,你不能做奇怪的魔法。
chan int不是int就像func(map[float64]bool) complex128不是int。
标签: go type-conversion channel