为了账号安全,请及时绑定邮箱和手机立即绑定

在 golang 中将 chan 转换为 non chan

在 golang 中将 chan 转换为 non chan

Go
HUX布斯 2021-10-18 10:16:08
是否可以让函数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 assignmentresult <- funcWithChanResult() // invalid operation: result <- funcWithChanResult() (send to non-chan type int)完整代码:package mainimport (    "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())}
查看完整描述

1 回答

?
Helenr

TA贡献1780条经验 获得超4个赞

Achan int是int值的通道,它不是单个int值,而是值的来源int(或者也是目标,但在您的情况下,您将其用作来源)。


因此,您无法转换chan int为int. 你可以做什么,可能你的意思是使用int从 a 接收到的值(类型)chan int作为int值。


这不是问题:


var result int

ch := funcWithChanResult()

result = <- ch

或更紧凑:


result := <- funcWithChanResult()

将此与return声明结合起来:


func funcWithNonChanResult() int {

    return <-funcWithChanResult()

}

输出(如预期):


Received first int: 123

Received second int: 123

在Go Playground上尝试修改后的工作示例。


查看完整回答
反对 回复 2021-10-18
  • 1 回答
  • 0 关注
  • 173 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信