在golang中将chan转换为非chan

Max*_*mov 4 channel type-conversion go

是否可以让函数funcWithNonChanResult具有以下接口:

func funcWithNonChanResult() int {
Run Code Online (Sandbox Code Playgroud)

如果我想让它使用funcWithChanResult接口函数:

func funcWithChanResult() chan int {
Run Code Online (Sandbox Code Playgroud)

换句话说,我可以以某种方式转换chan intint?或者我必须chan int在所有使用的函数中都有结果类型funcWithChanResult

目前,我试过这些方法:

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)
Run Code Online (Sandbox Code Playgroud)

完整代码:

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())
}
Run Code Online (Sandbox Code Playgroud)

操场

icz*_*cza 6

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

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

这不是问题:

var result int
ch := funcWithChanResult()
result = <- ch
Run Code Online (Sandbox Code Playgroud)

或者更紧凑:

result := <- funcWithChanResult()
Run Code Online (Sandbox Code Playgroud)

将此与return声明结合起来:

func funcWithNonChanResult() int {
    return <-funcWithChanResult()
}
Run Code Online (Sandbox Code Playgroud)

输出(如预期):

Received first int: 123
Received second int: 123
Run Code Online (Sandbox Code Playgroud)

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