卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章78374本站已运行447

如何使用 chan 作为 Golang 函数的参数?

如何使用 chan 作为 golang 函数的参数?

如何使用 chan 作为 Golang 函数的参数?

在 Golang 中,chan 类型代表一个通信通道,用于在 goroutine 之间发送和接收数据。它可以作为函数参数传递,以便函数可以与其他 goroutine 进行通信。

要点:

  • chan 在作为函数参数传递时,只能使用单向模式。
  • 函数必须使用 select 语句从通道中接收或发送数据。
  • Goroutine 可以通过向通道发送或从通道接收数据来与函数进行通信。

代码示例:

立即学习“go语言免费学习笔记(深入)”;

package main

import (
    "fmt"
    "time"
)

func receive(ch <-chan int) {
    for {
        i, ok := <-ch
        if !ok {
            fmt.Println("Channel is closed")
            return
        }
        fmt.Println("Received:", i)
    }
}

func main() {
    ch := make(chan int)
    go receive(ch)

    for i := 0; i < 5; i++ {
        ch <- i // Send data to the channel
    }

    close(ch) // Close the channel to signal the end of data transmission
    time.Sleep(1 * time.Second) // Give the receiver time to finish
}

解释:

  • receive 函数从只读通道 ch 接收数据。
  • main 函数创建通道 ch,启动 receive goroutine,向通道发送数据,然后关闭通道。
  • select 语句用于从通道接收数据,直到通道关闭。
  • 输出:

    Received: 0
    Received: 1
    Received: 2
    Received: 3
    Received: 4
    Channel is closed
卓越飞翔博客
上一篇: 如何使用类型推断来推断匿名函数的类型?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏