如何使用 chan 作为 Golang 函数的参数?
在 Golang 中,chan 类型代表一个通信通道,用于在 goroutine 之间发送和接收数据。它可以作为函数参数传递,以便函数可以与其他 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 }
解释:
输出:
Received: 0 Received: 1 Received: 2 Received: 3 Received: 4 Channel is closed
以上就是如何使用 chan 作为 Golang 函数的参数?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号