Pointers in the Go Programming Language(golang)
Like many other programming languages, there are two ways in which we can pass data in Go. You can either pass by value where Go will make a literal copy of the data you want to use(this uses more memory because it is making a copy of the data) or you can pass by reference where you are referring to the address in memory in which the data itself is stored rather than making a copy of the original data. When you pass by reference any changes made to the data effect where it is originally stored as they’re both pointing to the same address in memory.
Syntax for Pointers
When we want to point to certain elements there are two characters we use when using pointers. There is the “*” operator which declares that it will be a pointer to an address in memory. Then we have the “&” operator which will refer to the address of the original variable. Here is a very basic example of how we would go about using pointers:
Notice how the output for the j variable is giving us “0xc000016158” instead of 11. Why is that? It’s because we are assigning j to point to the address in memory where “i” is so that string of characters are actually it’s place in memory. If we wanted to extract the value from that address in memory, we would use the dereferencing operator which also happens to use this character: “*”. So to fix our previous example
var i int = 11
var j *int = &ifmt.Println(i)
fmt.Println(*j) //dereferencing operator placed before the variable//Output:
11
11
One thing to remember about pointers and to be careful of is that any changes made to the originating variable will also affect the any other variables that point to that variable.
Pointers as a Datatype
Pointers are a great use case when you’re dealing with structs. In the example below we are creating a struct that holds contains a number attribute and name attribute. You’ll be able to see how we use pointers to create new instances of the struct and see how we use the “new” syntax.
This is just a brief introduction into pointers, as you use them for projects and play around with them you can really see for yourself how great of a tool they are!