Michael
Michael

Reputation: 395

Pointers to structure in Go Language

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

Upvotes: 1

Views: 100

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65049

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.

Upvotes: 4

Related Questions