【问题标题】:Convert chan to non chan in golang在golang中将chan转换为非chan
【发布时间】:2015-08-31 20:41:32
【问题描述】:

是否可以让函数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

【问题讨论】:

  • Go 是静态类型的,你不能做奇怪的魔法。 chan int 不是 int 就像 func(map[float64]bool) complex128 不是 int

标签: go type-conversion channel


【解决方案1】:

chan intint 值的通道,它不是单个 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 上尝试修改后的工作示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-24
    • 2021-11-16
    • 2018-07-03
    • 2018-12-16
    • 2013-09-13
    • 2019-05-31
    • 1970-01-01
    • 2017-11-22
    相关资源
    最近更新 更多