Thursday, 15 April 2010

go - What do the terms pointer receiver and value receiver mean in Golang? -



go - What do the terms pointer receiver and value receiver mean in Golang? -

i've been getting errors go saying stuff pointer receivers , decided google terms mean , read different sources , documentation talking pointer receivers. example: http://golang.org/doc/faq , http://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go.

though, eventhough talk these terms failed define them precisely. though, context think difference between them defining variables pointers *mystruct vs mystruct. although, not 100% sure of difference, wanted more official or solid understanding of terms, specially difference (pointer receiver , value receiver). if possible simple illustration code showing difference in go awesome! (and necessary understand this)

like example, confusing me is, difference between term pointer , pointer receiver? or value , value receiver? term receiver add together these concepts?

since clarified you're confused term receiver , not pointer/value distinction. in go "receiver" refers value method defined on, purposes of interfaces. can think of receiver special case of first argument function.

func (m mystruct) dostuff()

this what's known "value receiver", defined on value mystruct. functionally identical to:

func dostuff(m mystruct)

except:

with "receiver" phone call function ".", in many oo languages:

m := mystruct{} m.dostuff() // opposed dostuff(m)

the set of methods type receiver on defines interface implements:

type doesstuff interface { dostuff() } func dosomething(d doesstuff) { d.dostuff() } func main() { m := mystruct{} dosomething(m) }

so what's pointer receiver? looks this:

func (m *mystruct) dootherstuff()

the difference difference between pointer , value. though minor semantic changes occur. go auto address , auto-dereference pointers (in cases) m := mystruct{}; m.dootherstuff() still works since go automatically (&m).dootherstuff() you. (naturally, you're free m := &mystruct{}; m.dootherstuff well). further, interface defined on pointer, so:

type doesotherstuff interface { dootherstuff() } func dosomethingelse(d doesotherstuff) { d.dootherstuff() } func main() { m := mystruct{} // dosomethingelse(m) fail since because interface // doesotherstuff defined on pointer receiver , value dosomethingelse(&m) }

if you're still confused when utilize pointer receiver versus variable receiver, short reply is: pointer receiver. long reply has been answered several times, i'll link here because easy find in history.

pointers go

No comments:

Post a Comment