drvvepadi289421028 2015-06-16 06:51
浏览 198
已采纳

在golang中将chan转换为non chan

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条回答 默认 最新

  • duanan1946 2015-06-16 07:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路