Home »
Golang
Go Pointers
Last Updated : July 17, 2025
In Go, pointers allow you to store and manipulate the memory address of a variable. They are useful when you want to modify data inside a function or avoid copying large values.
What is a Pointer?
A pointer holds the memory address of a variable. In Go, the &
operator gives the address of a variable, and the *
operator is used to access the value stored at that address (dereferencing).
Example
The following example demonstrates the usage of a pointer:
package main
import "fmt"
func main() {
x := 10
ptr := &x // pointer to x
fmt.Println("Value of x:", x)
fmt.Println("Address of x:", ptr)
fmt.Println("Value via pointer:", *ptr) // dereferencing
}
When executed, this program outputs something like:
Value of x: 10
Address of x: 0xc000012090
Value via pointer: 10
Modifying Value Using Pointer
When a pointer is passed to a function, it can be used to modify the original variable's value.
Example
This function doubles the value of the passed variable using a pointer:
package main
import "fmt"
func double(num *int) {
*num = *num * 2
}
func main() {
val := 5
fmt.Println("Before:", val)
double(&val)
fmt.Println("After:", val)
}
When executed, this program outputs:
Before: 5
After: 10
Nil Pointers
A pointer that does not point to any memory location is called a nil
pointer. You should always check for nil
before dereferencing to avoid runtime errors.
Example
The following example demonstrates the usage of nil pointer:
package main
import "fmt"
func main() {
var ptr *int
if ptr == nil {
fmt.Println("Pointer is nil")
}
}
Output:
Pointer is nil
Pointers with Structs
Pointers are often used with structs to modify their fields without copying the entire struct.
Example
The following example demonstrates the usage of pointers with structs:
package main
import "fmt"
type Student struct {
name string
age int
}
func updateAge(s *Student, newAge int) {
s.age = newAge
}
func main() {
s := Student{name: "Anjali", age: 20}
fmt.Println("Before:", s.age)
updateAge(&s, 22)
fmt.Println("After:", s.age)
}
Output:
Before: 20
After: 22
Exercise
Select the correct answers to test your understanding of pointers in Go.
- What does the
&
operator do?
- Which statement correctly modifies a variable via a pointer?
- What is the default value of an uninitialized pointer in Go?
Advertisement
Advertisement