What is Pointer in Go: Simple Explanation and Example
In Go, a
pointer is a variable that stores the memory address of another variable. It allows you to directly access or modify the original data by referring to its location in memory.How It Works
Think of a pointer like a street address for a house. Instead of carrying the house itself, you carry the address so you can find it anytime. In Go, a pointer holds the memory address where a variable's value is stored.
This means you can use a pointer to look up or change the value stored at that address without copying the value itself. This is useful when you want to save memory or update data directly.
Example
This example shows how to create a pointer, access the value it points to, and change that value through the pointer.
go
package main import "fmt" func main() { x := 10 p := &x // p holds the address of x fmt.Println("Value of x:", x) // prints 10 fmt.Println("Pointer p points to:", *p) // prints 10 *p = 20 // change value at address p points to fmt.Println("New value of x:", x) // prints 20 }
Output
Value of x: 10
Pointer p points to: 10
New value of x: 20
When to Use
Use pointers in Go when you want to:
- Modify a variable inside a function without returning it.
- Save memory by avoiding copying large data structures.
- Work with shared data safely and efficiently.
For example, if you pass a large struct to a function, using a pointer lets the function change the original struct without making a copy.
Key Points
- A pointer stores the memory address of a variable.
- Use
&to get the address of a variable. - Use
*to access or change the value at that address. - Pointers help avoid copying data and allow direct modification.
Key Takeaways
A pointer holds the memory address of a variable in Go.
Use & to get a variable's address and * to access or modify its value.
Pointers let you change data directly and save memory by avoiding copies.
They are useful for passing large data or modifying variables inside functions.