Home > Software design >  Pass channel in to method or access nested struct object directly
Pass channel in to method or access nested struct object directly

Time:04-13

The base code I was working off of passes the channel in to multiple methods. The same channel is also accessible through nested structs. I can access the same logCh by using p.Server.logCh. I know channels are pretty lightweight to pass around but is there a reason not to access it directly? There will be multiple concurrent goroutines accessing this same channel.

type Processor struct { 
    Server *Server 
}

func (p *Processor) Process(messagesCh <-chan storage.QueueMessage, logCh chan<- model.Log, done chan struct{}) { }

CodePudding user response:

Channels are designed to be safe to copy and for concurrent read/writes. So your question is more a matter of coding convenience.

To make code more readable, see the suggestion below.


If you find you are frequently referencing a common parameter, it may make sense to move it to the receiver struct e.g.

type Processor struct { 
    Server     *Server
    MessagesCh <-chan storage.QueueMessage
}

either make it a public field, so it can be set later. Or use a "constructor" to build the channel at startup and store it in the struct (maybe even as a private field).

Then the channel is accessible to all methods more readily.

  • Related