Structs and Pointers




Pointers



A pointer in GO, is pretty much the same is it is in other programming languages. The contents of a pointer is the memory address of the thing the pointer references. To dereference a pointer, I have to use the * prefix operator. To get the address something, I have to use the & prefix operator.


var apples = 7 // just a variable
var *pointerToApples = &apples // get a pointer (*) to apples by getting the address (&) of apples.


If I try to do this with a struct, this means the pointer references the elements of the struct, not the struct as a whole.

type aStruct { // define the struct
junk1 int
junk2 int
}

var item aStruct // instantiate struct
item.junk1 = 1 // set some values
item.junk2 = 2
var pointer *aStruct = &item // try to get a pointer to struct by getting its address
fmt.Println(*pointer.junk2) //
ERROR


The way to solve this problem is to wrap the pointer in parentheses.

fmt.Println((*pointer).junk2) // get the pointer to the entire struct to reference any of its elements.


There is another way. Once I have a pointer to the struct, I can just use dot notation normally, which simplifies the syntax to:


fmt.Println(pointer.junk2)

Structs, Pointers, and Functions



To get back to my original issue, in order to change a value in a struct passed as an argument, you can pass a pointer to the struct:

func myFunction(item *aStruct){ // pass the struct by reference, not value
item.junk1 = 7 // modifies the struct.
}


myFunction(&item) // pass the address of the struct to the function.


Even though this is similar to how many other languages work, it's still not very functional. I probably won't be using this ability of GO often. It is, however, still useful if you end up with memory pressure because you keep passing copies of large structs to functions rather than pointers.

That's it for today. Next time, I continue my examination of structs.







This site does not track your information.