Home >Backend Development >Golang >golang function channel passed as parameter
In Go, we can easily share and pass data between functions by passing function channels as function parameters using the chan keyword. The specific steps are as follows: Create a channel to pass a specific type of data. Pass the channel as a parameter in the function using the chan keyword and the channel name. Use a one-way channel
In the Go language, we can pass function channels as function parameters, which can be passedchan
Keyword implementation. This makes it easy to share and pass data between functions.
Syntax:
func functionName(channelName chan type)
Where:
channelName
is the name of the channeltype
is the type of data transmitted in the channel Practical example:
Consider the following example where we create a channel to pass a string :
package main import ( "fmt" "time" ) // 创建一个通道来传递字符串 var messages chan string func main() { // 开启一个 goroutine 将数据发送到通道中 go func() { for { messages <- "Hello, world!" time.Sleep(1 * time.Second) } }() // 开启一个 goroutine 从通道中接收数据 go func() { for { // 从通道中接收数据,并打印出来 msg := <-messages fmt.Println(msg) } }() // 等待 10 秒来查看输出 time.Sleep(10 * time.Second) }
In this example:
messages
which will pass the string. to receive data so that only one value can be received at a time.
fmt.Println
to print messages received from the channel. time.Sleep
to delay the goroutine to see the output. The above is the detailed content of golang function channel passed as parameter. For more information, please follow other related articles on the PHP Chinese website!