tags:

views:

67

answers:

2

Sorry for the novice syntax question.

How do how create an array of channels in go?

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

That is, replacing the above five lines in one array of channels of size 5?

Many thanks.

+1  A: 

Should be var chans [5]chan int

nico
thanks. Is there a way to "make" them all at once, or should I iterate and create one by one.
eran
In the answer given, you don't have to make anything. You already have an array of 5 channels. If you wanted a slice instead, you could say chans := make([]chan int, 5). No iteration there either.
Evan Shaw
you should mention that the channels in the array are all `nil`, and you still have to go through and make each channel individually
newacct
+2  A: 

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)
}
MizardX
Why is your solution better than Chickencha's succinct and idiomatic `chans := make([]chan int, 5)`?
peterSO
If the channels are not explicitly allocated with `make(chan int)`, they will default to `nil`.
MizardX