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

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 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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.