在golang中将chan转换为non chan

Convert chan to non chan in golang

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

func funcWithNonChanResult() int {

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

func funcWithChanResult() chan int {

换句话说,我能否以某种方式将 chan int 转换为 int?或者我必须在所有使用 funcWithChanResult?

的函数中具有 chan int 结果类型

目前,我尝试了这些方法:

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)

完整代码:

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

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

因此您无法将 chan int 转换为 int。你可以做什么,可能你的意思是使用从 chan int 收到的值(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.

上尝试修改后的工作示例