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);
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.
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.
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.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With