gochannelbuffered

Create a slice of buffered channel in golang


I couldn't find a way to create a slice of buffered channels in golang. I know how to create slice of unbuffered channel given as below

type ch chan int
channels := make([]ch,5)

Solution

  • This statement channels := make([]ch,5) is simply allocating the container (the slice of channels which has a length of 5). In addition to that you have to initialize each channel individually which is when you would declare them as buffered rather than unbuffered. So extending your example just do this:

    for i, _ := range channels {
         channels[i] = make(chan int, BufferSize)
    }