douzhaobo6488 2018-11-12 17:30
浏览 4
已采纳

在Go中打印频道内容

How can I print the contents of a channel in Go?

For example:

package main

import "fmt"

func main() {
    ok := make(chan int)
    ok <- 1
    x := <- ok
    fmt.Println(x)
}

As I understand, ok is a channel which can store an integer value. So, how can I print its contents?

fmt.Println(ok) doesn't print the value stored inside the channel.

Thanks.

  • 写回答

2条回答 默认 最新

  • douqiang6036 2018-11-12 17:48
    关注

    Channels make(chan int) has implicit size zero ( ref: https://golang.org/ref/spec#Making_slices_maps_and_channels)

    A channel of size zero is unbuffered. A channel of specified size make(chan int, n) is buffered. See http://golang.org/ref/spec#Send_statements for a discussion on buffered vs. unbuffered channels. The example at http://play.golang.org/p/VZAiN1V8-P illustrates the difference.

    Here, channel <-ok or ok <- will be blocked until someone processes it (concurrently). So, change ok := make(chan int) to ok := make(chan int,1)

    package main
    
    import "fmt"
    
    func main() {
        ok := make(chan int, 1)
        ok <- 1
        x := <- ok
        fmt.Println(x)
    }
    

    Or concurrently proccess it

    package main
    
    import "fmt"
    
    func main() {
        ok := make(chan int)
        go func(){
           ok <- 1
        }()
        x := <- ok
        fmt.Println(x)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端