I can initialise a buffered string channel like this
queue := make(chan string, 10)
But how to initialise a buffered channel in a struct in Go ? Basically I want to allocate memory to a buffered string channel. But initially in the struct I would just define it and in struct initialisation, I would like to allocate memory to it
type message struct {
queue *chan string
// or will it be
//queue []chan string
}
func (this *message) init() {
queue = make(chan string,10)
this.queue = &queue
}
Do this:
type message struct {
queue chan string
}
func (m *message) init() {
m.queue = make(chan string, 10)
}
There's no need to take the address of the channel in this scenario.
The same way:
type message struct {
queue chan string
}
func (m *message) init() {
m.queue = make(chan string, 10)
}
But you seem to be a bit confused about what a channel is. *chan string
is a valid construct in Go, but usually unnecessary. Just use a normal chan string
--no need for a pointer.
// or will it be
//queue []chan string
This would be an array of channels, which is also valid, but not what you want in this case.
A channel is not an array. It's more like a stream (as you might get when you read a file, or a network connection). But don't take that analogy too far, either.