将通道传递给方法或直接访问嵌套的结构对象。

huangapple go评论71阅读模式
英文:

Pass channel in to method or access nested struct object directly

问题

我正在翻译以下内容:

我正在使用的基础代码将通道传递给多个方法。同样的通道也可以通过嵌套结构进行访问。我可以通过使用p.Server.logCh来访问相同的logCh。我知道通道在传递时非常轻量级,但是是否有理由不直接访问它?将有多个并发的goroutine访问这个相同的通道。

type Processor struct {
    Server *Server
}

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

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 &lt;-chan storage.QueueMessage, logCh chan&lt;- model.Log, done chan struct{}) { }

答案1

得分: 0

通道被设计为可以安全复制和并发读写的。所以你的问题更多是关于编码方便性的问题。

为了使代码更易读,请参考下面的建议。


如果你发现你经常引用一个常见的参数,将其移动到接收者结构体可能是有意义的,例如:

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

可以将其设置为公共字段,以便稍后设置。或者在启动时使用“构造函数”构建通道并将其存储在结构体中(甚至可以作为私有字段)。

然后通道更容易被所有方法访问。

英文:

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 &lt;-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.

huangapple
  • 本文由 发表于 2022年4月12日 21:40:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/71843792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定