Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make buffered channel after channel variable initialisation

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

}
like image 952
Tahseen Avatar asked Sep 26 '26 03:09

Tahseen


2 Answers

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.

like image 40
Flimzy Avatar answered Sep 27 '26 16:09

Flimzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!