Pointers in Go - When to use the ampersand and the asterisk?

Search for a command to run...

No comments yet. Be the first to comment.
It's Candy Again! Hello Hashnoders! After having so much fun building MoodPraiser for the #harperdbhackathon, and here I am again for the #auth0hackathon! Big thanks to Hashnode for hosting these events and this time 'round I even persuaded friends t...

What is a Lightning Talk? Stealing this from Wikipedia: Lightning talks are designed to be short presentations between five and ten minutes long, but are usually capped at five minutes. Lightning talks usually accept sign-ups after the conference h...

Lately, I've been setting up my new Mac and thought that it would be a good chance to log down what I needed to install for future reference. This post will be updated from time to time as I install back all the apps that I use daily. Must-to-have ap...

Here comes Piglet!

Looking back, this might be a dumb question, but that’s what blog notes are for 🤣
&: Used as an operator to get the address of a variable
* in Type: Used to define the type as a pointer (e.g., *int)
* in Expression: Used as an operator to dereference
In short * does two things and & can only to that one thing.
Can be run here: https://go.dev/play/p/XdA4_qdt7lR
package main
import "fmt"
func main() {
value := 42 // The original data
// --- 1. & gets the address ---
address := &value
fmt.Printf("1. & Action: get Address: %p\n", address)
// --- 2. * defines the Pointer Type ---
// 'p' is declared as the TYPE '*int' (a pointer type).
var p *int = address
fmt.Printf("2. Type Definition: 'p' is of TYPE %T\n", p)
// --- 3. * dereferences ---
// The '*' operator reads the value at the address stored in 'p'.
retrievedValue := *p
fmt.Printf("3. * Operator: Value retrieved via dereference: %d\n", retrievedValue)
}
NO, the ampersand will never be used in type definitions, because it only does one thing, it gets the address of the variable. For type definitions we use *.
// 1. * used for type definition
func updateScore(p *int) {
*p = 99 // 2. * used for dereference and change the value at that address
}
If *p = 99 feels confusing, read this article: https://dave.cheney.net/2017/04/26/understand-go-pointers-in-less-than-800-words-or-your-money-back