Convert chan to non chan in golang

狂风中的少年 提交于 2019-12-05 14:56:05

A chan int is a channel of int values, it is not a single int value but a source of int values (or also a target, but in your case you use it as source).

So therefore you can't convert chan int to int. What you can do and probably what you mean is use a value (of type int) received from a chan int as an int value.

This is not a problem:

var result int
ch := funcWithChanResult()
result = <- ch

Or more compact:

result := <- funcWithChanResult()

Combine this with the return statement:

func funcWithNonChanResult() int {
    return <-funcWithChanResult()
}

Output (as expected):

Received first int: 123
Received second int: 123

Try your modified, working example on the Go Playground.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!