I just started diving into Go recently and I have one major point of confusion: I am struggling to understand when exactly it is necessary to dereference a pointer explicitly.
For example I know that the
. operator will handle dereferencing a pointer
ptr := new(SomeStruct) ptr.Field = "foo" //Automatically dereferences
In what other scenarios does go do this? It seems to for example, with arrays.
ptr := new(int) ptr = 1
I have been unable to find this in the spec, the section for pointers is very short and doesn’t even touch dereferencing. Any clarification of the rules for dereferencing go’s pointers would be great!
The selector expression (e.g.
x.f) does that:
Selectors automatically dereference pointers to structs. If
xis a pointer to a struct,
x.yis shorthand for
(*x).y; if the field
yis also a pointer to a struct,
(*(*x).y).z, and so on. If
xcontains an anonymous field of type
Ais also a struct type,
x.fis a shortcut for
The definition of the index expressions specifies that an array pointer may be indexed:
For a of pointer to array type:
a[x]is shorthand for
Answered By – zzzz
Answer Checked By – Willingham (GoLangFix Volunteer)