Go Asterisk and Ampersand Cheatsheet

· Code Samples Go

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.

author image

About Joseph Spurrier

I'm passionate about building solutions to automate tasks and improve efficiency. I worked for a few companies in the digital healthcare space. My education is in forensics. Tech guy. Traveler. Runner. Guitar player. Scotch and beer enthusiast. GitHub LinkedIn Twitter Google+

Share this post

Comments powered by Disqus