Go Asterisk and Ampersand Cheatsheet
In the Go programming language (Golang), there are two symbols you need to understand when dealing with pointers: the asterisk and ampersand. I’m going to let the code do most of the talking, but there are essentially 4 different ways (illustrated by each of the tests) to pass around variables.
Different Tests with the Asterisk and Ampersand
- Test 1 - Store the value and then pass it to a function.
- Test 2 - Store the *pointer address and then it pass to a function.
- Test 3 - Store the value and then pass the &pointer address to a function.
- Test 4 - Store the &pointer address and then pass the *value to a function.
In each of the tests, the values are outputted three times: when created, when modified by the updatePerson() function, and then after the updatePerson() function.
There also are a few differences to examine between the tests:
- If variables are passed by value to the updatePerson() function, the 3rd output will be different from the 2nd output.
- If variables are passed by value to the printPerson() function, the String() method will not be used by fmt.Printf().
Side note: If you are having trouble deciding whether to define methods on values or pointers, check out the Golang FAQs.
A great article to read with a more in-depth explanation is Understanding Pointers and Memory.