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([5][5]int) ptr[0][0] = 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!
Go performs automatic dereferencing for struct data type in its specification. Hence, you do not need to de-reference it explicitly. Quote: 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).
Pointers can be dereferenced by adding an asterisk * before a pointer.
In Go a pointer is represented using the * (asterisk) character followed by the type of the stored value. In the zero function xPtr is a pointer to an int . * is also used to “dereference” pointer variables. Dereferencing a pointer gives us access to the value the pointer points to.
Dereferencing is used to access or manipulate data contained in memory location pointed to by a pointer. *(asterisk) is used with pointer variable when dereferencing the pointer variable, it refers to variable being pointed, so this is called dereferencing of pointers.
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 fieldyis also a pointer to a struct,x.y.zis shorthand for(*(*x).y).z, and so on. Ifxcontains an anonymous field of type*A, whereAis also a struct type,x.fis a shortcut for(*x.A).f.
The definition of the indexing operation specifies that an array pointer may be indexed:
For a of type
Aor*AwhereAis an array type, or for a of typeSwhereSis a slice type
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With