×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang program to create an array of channels

Here, we are going to learn how to create an array of channels in Golang (Go Language)?
Submitted by Nidhi, on April 04, 2021 [Last updated : March 04, 2023]

How to create an array of channels in Golang?

Problem Solution:

In this program, we will create an array of channels. Then we will send and receive values of an array of channels and print the values on the console screen.

Program/Source Code:

The source code to create an array of channels is given below. The given program is compiled and executed successfully.

Golang code to create an array of channels

// Golang program to create an
// array of channels

package main

import "fmt"

func SetChannelArray(chnl []chan int) {
	chnl[0] <- 10
	chnl[1] <- 20
	chnl[2] <- 30
	chnl[3] <- 40
	chnl[4] <- 50
}

func main() {
	var chans = []chan int{
		make(chan int),
		make(chan int),
		make(chan int),
		make(chan int),
		make(chan int),
	}
	go SetChannelArray(chans)

	fmt.Println(<-chans[0])
	fmt.Println(<-chans[1])
	fmt.Println(<-chans[2])
	fmt.Println(<-chans[3])
	fmt.Println(<-chans[4])
}

Output:

10
20
30
40
50

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.

In the main() function, we created an array of channels. Here, we send values to the array of channels in the SetChannelArray() function. After that, we printed the values of the array of channels on the console screen.

Golang Channels Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.