当前位置: 首页 > 面试题库 >

在golang中将chan转换为non chan

崔高远
2023-03-14
问题内容

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

func funcWithNonChanResult() int {

如果我希望它funcWithChanResult在接口中使用function :

func funcWithChanResult() chan int {

换句话说,我可以以某种方式转换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)

完整代码:

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

操场


问题答案:

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

因此,您不能转换chan intint。您可以做的并且可能是您的意思是使用int从a接收的值(类型)chan 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上尝试修改后的工作示例



 类似资料:
  • 问题内容: 我需要在Golang中将转换为。是否有可能转换到在Golang无须转换为或第一? 需要一个。需要一个。 问题答案: 一线的答案是。 无论如何,甚至在标准库函数(例如)内部都有很多转换,因此您有一些选择(尝试使用Go Playground ): 1-您可以编写转换函数( 最快 ): 2-您可以使用 ( 慢 ) 参见内部: 3-您可以使用 ( 快速 ) 参见内部: 4-您可以使用( 更快

  • 问题内容: 无法将image.image转换为[] byte。问题点用虚线包裹。 基本上,我需要new_image为[] byte格式,以便可以将其发送到我的S3存储桶。 谢谢您的帮助。 问题答案: 您需要一个byte.Buffer,而不是bufio.Writer。bytes.Buffer在需要写入器的写入器时使用。bufio.Writer只是在将数据转发到另一个写入器之前将其缓存在内存中。

  • 问题内容: 我正在尝试找到转换的最佳方法 键入字符串。我尝试使用marshall转换为json以保留格式,然后转换回字符串,但这未成功。更具体地说,我正在尝试将包含键和值的映射转换为字符串以容纳https://www.nomadproject.io/docs/job- specification/template.html#environment-variables https://github.

  • 问题内容: 我正在尝试将字节切片转换为GoLang中的。我找不到在线解决此问题的方法。我见过先转换为字符串然后转换为a的建议,但这似乎不起作用,它失去了它的值,最后以零结束。 例: 而且它不起作用… 问题答案: 例如, 输出:

  • 问题内容: 我正在使用github.com/fatih/structs包将struct的所有字段的值转换为函数。看这里。这工作正常,但最终我想通过使用csv包将值写入csv文件。该功能需要作为输入。 简而言之:我如何轻松地将的输出转换为字符串数组? 问题答案: 即使所有值都是具体类型,也不能简单地转换为,因为这两种类型具有不同的内存布局/表示形式。 您必须定义如何用值表示不同类型的值。 最简单和明

  • 问题内容: 我想在下面的代码中改进getCustomerFromDTO方法,我需要从interface {}创建一个结构,目前我需要将该接口编组为byte [],然后将数组解组为我的结构-必须有更好的方法。 我的用例是,我通过rabbitmq发送结构,然后使用具有其他特定于域的数据的通用DTO包装器来发送它们。当我从Rabbit MQ接收DTO时,消息下方的一层将被封送给我的DTO,然后我需要从该