Pointers
A pointer stores the memory address of a variable. In Go, you can use pointers to modify a variable's value from within a function, or to avoid copying large data structures.
Syntax
// Declare a pointer type var p *int // pointer to int (zero value is nil) // Use the address operator & to get a variable's address x := 42 p = &x // assign the address of x to p // Use the dereference operator * to read or modify the value fmt.Println(*p) // 42 (the value of x) *p = 100 // change the value of x to 100 // Use new() to allocate a new variable on the heap p2 := new(int) // type *int, value is 0 *p2 = 55
Syntax Reference
| Operator / Function | Description |
|---|---|
| &variable | Returns the memory address of a variable as a pointer type (*T). |
| *pointer | Reads or modifies the value that the pointer points to. Also called dereferencing. |
| *type | Declares a pointer type. Example: var p *int. |
| new(type) | Allocates a zero value of the specified type on the heap and returns a pointer to it. |
| nil | The zero value for a pointer. Indicates that no address has been assigned. |
Sample Code
package main
import "fmt"
// A function that modifies the caller's variable via a pointer
func double(n *int) {
*n = *n * 2
}
// Pass by value (the original is not changed because a copy is made)
func doubleCopy(n int) {
n = n * 2
}
func main() {
x := 10
// Pass by value
doubleCopy(x)
fmt.Println(x) // 10 (unchanged)
// Pass by pointer
double(&x)
fmt.Println(x) // 20 (changed!)
// Basic pointer operations
p := &x
fmt.Printf("Address: %p\n", p) // prints the memory address
fmt.Printf("Value: %d\n", *p) // 20
// Using new()
p2 := new(int)
*p2 = 99
fmt.Println(*p2) // 99
// nil check
var p3 *int
if p3 == nil {
fmt.Println("p3 is nil")
}
}
Notes
Go pointers are designed to be safe — unlike C or C++, pointer arithmetic (adding or subtracting from an address) is not allowed. When passing large structs to a function, using a pointer avoids the overhead of copying the data.
Dereferencing a nil pointer (e.g., *p) causes a panic. Always check for nil or ensure the pointer is initialized before using it.
Pointers are commonly used with structs and method receivers, making them a frequently encountered pattern in Go code.
If you find any errors or copyright issues, please contact us.