Convert chan to non chan in golang

蓝咒 提交于 2019-12-07 07:51:14

问题


Is it possible to let function funcWithNonChanResult have the following interface:

func funcWithNonChanResult() int {

And if I want it to use function funcWithChanResult with the interface:

func funcWithChanResult() chan int {

In other words, can I somehow convert chan int to int? Or I must have chan int result type in all the functions which use funcWithChanResult?

Currently, I tried these methods:

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)

Full code:

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())
}

Playground


回答1:


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.



来源:https://stackoverflow.com/questions/30860644/convert-chan-to-non-chan-in-golang

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