英文:
Pointers to structure in Go Language
问题
这是我的代码:
package main
import "fmt"
type Message struct {
Text []byte
Tag string
}
func main() {
var m Message
pkt := []byte("Hey")
editMessage(&m, &pkt)
fmt.Println(string(m.Text))
}
func editMessage(m *Message, pkt *[]byte) {
m.Text = *pkt
}
我得到了预期的输出:"Hey"。
如果我将m.Text = *pkt
改为(*m).Text = *pkt
,它也能正常工作!
哪个是正确/更高效的版本?还是它只是一个快捷方式?
这个问题并不总是有效,如果我在一个函数中使用c *net.Conn
作为输入,我必须使用something := (*c).RemoteAddr()
才能使其工作。
谢谢。
英文:
this is my code:
package main
import ("fmt")
type Message struct {
Text []byte
Tag string
}
func main() {
var m Message
pkt := []byte("Hey")
editMessage(&m, &pkt)
fmt.Println(string(m.Text))
}
func editMessage(m *Message, pkt *[]byte) {
m.Text = *pkt
}
And I get "Hey" as expected on the output.
If I change m.Text = *pkt
with (*m).Text = *pkt
It works as well!
Which is the correct/more efficient version? Or is it just a shortcut?
This thing doesn't now work all the time, if I use
c *net.Conn
as input in a function, I must use
something := (*c).RemoteAddr()
to get it working.
Thank you
答案1
得分: 4
如果你参考了Golang语言规范-方法值部分,你会注意到这段引用(重点是我的):
与选择器一样,使用指针引用一个具有值接收器的非接口方法将自动解引用该指针:pt.Mv等同于(*pt).Mv。
因此,你的指针会自动解引用。
net.Conn
是一个接口...因此,你必须手动解引用指针才能使其工作。
英文:
If you refer to the Golang Language Specification - Method values section, you'll note this quote (emphasis mine):
> As with selectors, a reference to a non-interface method with a value receiver using a pointer will *automatically dereference that pointer: pt.Mv is equivalent to (pt).Mv.
Thus, your pointer is being automatically dereferenced for you.
net.Conn
is an interface .. and as such, you must manually dereference the pointer in order for this to work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论