
如何使用 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,启动receivegoroutine,向通道发送数据,然后关闭通道。 -
select语句用于从通道接收数据,直到通道关闭。 -
输出:
Received: 0 Received: 1 Received: 2 Received: 3 Received: 4 Channel is closed










