Go语言中的结构体指针

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

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.

huangapple
  • 本文由 发表于 2015年3月24日 18:55:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/29230739.html
匿名

发表评论

匿名网友

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

确定