Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate an array of channels

Tags:

arrays

go

channel

How to create an array of channels?

For example: replace the following five lines with an array of channels, with a size of 5:

var c0 chan int = make(chan int); var c1 chan int = make(chan int); var c2 chan int = make(chan int); var c3 chan int = make(chan int); var c4 chan int = make(chan int); 
like image 327
eran Avatar asked May 23 '10 18:05

eran


People also ask

How do I allocate memory in an array in Golang?

In Go dynamic memory block is allocated mainly using new and make. New allocates exact one memory block that is used to create struct type value, whereas, make creates more than one memory block and returns the reference, like a slice, map or channel value.

What is difference between Array and slice in Golang?

Slices in Go and Golang The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.

What is buffered channel in Golang?

Buffered channels allows to accept a limited number of values without a corresponding receiver for those values. It is possible to create a channel with a buffe. Buffered channel are blocked only when the buffer is full. Similarly receiving from a buffered channel are blocked only when the buffer will be empty.


1 Answers

The statement var chans [5]chan int would allocate an array of size 5, but all the channels would be nil.

One way would be to use a slice literal:

var chans = []chan int {    make(chan int),    make(chan int),    make(chan int),    make(chan int),    make(chan int), } 

If you don't want to repeat yourself, you would have to iterate over it and initialize each element:

var chans [5]chan int for i := range chans {    chans[i] = make(chan int) } 
like image 59
Markus Jarderot Avatar answered Oct 06 '22 01:10

Markus Jarderot