英文:
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 = *<-in
mb := *<-in
//mb := <-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规范)。
这意味着*<-in
将对*MessageBroker
指针进行解引用,并给你一个MessageBroker
类型的值。
所以,再看一下你的示例:
//var mb MessageBroker = *<-in // mb被显式声明为MessageBroker类型
mb := *<-in // mb使用短变量声明隐式声明为MessageBroker类型
//mb := <-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 <-chan *MessageBroker) {
We can see that <-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 *<-in
will dereference the *MessageBroker
pointer and give you a value of type MessageBroker
.
So, looking at your examples again:
//var mb MessageBroker = *<-in // mb is explicitly declared as a MessageBroker
mb := *<-in // mb is implicitly declared as a MessageBroker using short variable declaration
//mb := <-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 := "New message"
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论