Home >Backend Development >Golang >golang function channel passed as parameter

golang function channel passed as parameter

WBOY
WBOYOriginal
2024-04-22 18:36:01985browse

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

golang function channel passed as parameter

Function channels are passed as parameters in Go

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 channel
  • type 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:

  • We create a channel named messages which will pass the string.
  • We created two goroutines, one to send data to the channel and the other to receive data from the channel.
  • We use a one-way channel to receive data so that only one value can be received at a time.
  • Call fmt.Println to print messages received from the channel.
  • We use 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn