Im working through a Go Ebook
.
Here we are creating an array of pointers as so:
sampleArray := [5]*int{0: new(int), 1: new(int)}
As you can see index 0 and index 1 of sampleArray
contain initialized integers whereas the remaining indexes contain uninitialized integers.
Then they do the following operation:
*sampleArray[0] = 10
*sampleArray[1] = 20
With that, the values of sampleArray
should be:
[0] => address (integer pointer) -> 10
[1] => address (integer pointer) -> 20
[2] => nil (integer pointer)
[3] => nil (integer pointer)
[4] => nil (integer pointer)
My question is, why do we do this:
*sampleArray[0] = 10
*sampleArray[1] = 20
And not this:
sampleArray[0] = 10
sampleArray[1] = 20
To me it looks like we are assigning a value to a pointer which points to another pointer. Shouln't we be assigning the value to the actual memory reference?
Why not then?
&sampleArray[0] = 10
&sampleArray[1] = 20
Im extremely new to pointers so please any thourough assistance would be helpful
This is actually a good question.
The dereferencing operator *
has a lower precedence than array access (which in C is equivalent to pointer deref). So *a[x]
in Go means "dereference *a[x]
" and not "dereference a
and take element x".
Hope this clarifies things.