Overview
The Basics of Pointers in Golang discusses pointers from the perspective of pass-by-reference and pass-by-value. However, I found myself confused while working with pointers, so I decided to summarize an overview of pointers.
What is a Pointer Type?
- A type of variable that stores a memory address.
Defining a Pointer Type
- Use
*to define it.
Address Operator and Dereference Operator
Address Operator &
- Generates a pointer type from any value and retrieves its address.
Dereference Operator *
- Accesses the value from a pointer type variable (dereferencing).
Pointer Type Variables
Structs and Pointers
Review of Structs
Structs and Pointers
Initializing Structs with Composite Literals
Initializing Structs with new
Receiver and Pointer
Value Receiver
Pointer Receiver
Difference Between Value Receiver and Pointer Receiver
When you want to modify the values of a struct's fields within a function, use a pointer receiver. For reference types like map or chan, a value receiver is sufficient. However, this is not always the case when considering strict performance requirements.
If You Get Confused About Pointers
Refer back to the definitions of pointer types and the roles of operators mentioned earlier in this post.
References
- Go Pointers
- Qiita - Learning Pointers and Addresses in Go
- Qiita - Differences Between Ampersand (&) and Asterisk (*) in Go
- Qiita - Researching Go Structs
- [Go] Using Value and Pointer Methods in Structs
- Github golang/tour - tour: How do I print an address of the pointer to "Struct fields"? #226
- StackOverflow - Memory Address for Struct Not Visible