通过通道值的指针对本地变量进行赋值

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

Assignment to a local variable through a pointer from channel value

问题

在第45、46和47行,有三种不同的方式从消息代理中获取值。

//var mb MessageBroker = *<-in
mb := *<-in
//mb := <-in

这三种方式的结果完全相同。选择其中一种方式的重要性是什么?此外,我对为什么星号似乎没有任何区别感到困惑。

英文:

Code Here: http://play.golang.org/p/WjpgN_0AaP

On lines 45,46 and 47 there are three different ways to pull the value off the message broker.

//var mb MessageBroker = *&lt;-in
mb := *&lt;-in
//mb := &lt;-in	

All three of these have the exact same result. What is the significance of choosing one way over the other? Also, I'm confused as to why the asterix seemingly makes no difference.

答案1

得分: 2

看一下你的函数声明:

func (c *MyGui) Receive(in <-chan *MessageBroker) {

我们可以看到<-in会给你一个*MessageBroker类型的值,即指向MessageBroker结构体的指针。

在指针值前加上星号将对其进行解引用(参见Go规范)。

这意味着*&lt;-in将对*MessageBroker指针进行解引用,并给你一个MessageBroker类型的值。

所以,再看一下你的示例:

//var mb MessageBroker = *&lt;-in // mb被显式声明为MessageBroker类型
mb := *&lt;-in // mb使用短变量声明隐式声明为MessageBroker类型
//mb := &lt;-in // mb使用短变量声明隐式声明为*MessageBroker指针类型

前两个选项是相同的,但第三个选项中,mb将是指向结构体的指针。在你的特定情况下,它实际上并不重要,因为你只是打印Message

然而,如果你要更改消息,区别就会出现:

mb.Message := "New message"

如果mb的类型是MessageBroker,即结构体值类型,那么更改只会影响局部的mb变量,对Receive函数外部没有影响。

然而,如果mb的类型是*MessageBroker,你将更改通过通道接收到的同一个对象的实例。

英文:

Looking at the declaration of your function:

func (c *MyGui) Receive(in &lt;-chan *MessageBroker) {

We can see that &lt;-in will give you a value of type *MessageBroker, a pointer to a MessageBroker struct.

Putting an asterisk before a pointer value will dereference it (see Go spec)

That means *&lt;-in will dereference the *MessageBroker pointer and give you a value of type MessageBroker.

So, looking at your examples again:

//var mb MessageBroker = *&lt;-in // mb is explicitly declared as a MessageBroker
mb := *&lt;-in // mb is implicitly declared as a MessageBroker using short variable declaration
//mb := &lt;-in // mb is implicitly declared as a *MessageBroker pointer.

So, the two first options are identical, but the third will have mb being a pointer to the struct instead. In your particular case it doesn't really matter if it is a pointer or not; you are just printing the Message.

However, the difference would be if you were to change the message:

mb.Message := &quot;New message&quot;

If mb was of type MessageBroker, a struct value, then the change would just be for the local mb variable, but would have no effect outside of the Receive function.

However, if mb is of type *MessageBroker, you would change the same instance of the object as you received through the channel.

huangapple
  • 本文由 发表于 2014年4月23日 09:34:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/23233286.html
匿名

发表评论

匿名网友

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

确定