Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do Go's pointers dereference themselves

Tags:

pointers

go

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!

like image 885
Daniel Gratzer Avatar asked Nov 23 '12 17:11

Daniel Gratzer


People also ask

Does Golang automatically dereference?

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).

How do I dereference a pointer in Go?

Pointers can be dereferenced by adding an asterisk * before a pointer.

How do pointers work in Go?

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.

What is pointer dereferencing?

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.


1 Answers

The selector expression (e.g. x.f) does that:

Selectors automatically dereference pointers to structs. If x is a pointer to a struct, x.y is shorthand for (*x).y; if the field y is also a pointer to a struct, x.y.z is shorthand for (*(*x).y).z, and so on. If x contains an anonymous field of type *A, where A is also a struct type, x.f is a shortcut for (*x.A).f.

The definition of the indexing operation specifies that an array pointer may be indexed:

For a of type A or *A where A is an array type, or for a of type S where S is a slice type

like image 68
zzzz Avatar answered Sep 20 '22 00:09

zzzz