Go•Pointers
Go Pointers and Pass-by-Reference (* and &)
Go has pointers to control memory without pointer arithmetic, keeping memory access safe.
Syntax
ptr := &val
*ptr = 100
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| & | Address-of Operator | Returns memory address of variable. |
| * | Dereference Operator | Reads or writes value stored at pointer. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import "fmt"
// Mutates integer at memory address
func increment(valPtr *int) {
*valPtr = *valPtr + 1
}
func main() {
count := 41
ptr := &count
fmt.Printf("Initial Count: %d\n", count)
fmt.Printf("Memory Address: %p\n", ptr)
// Call function with pointer
increment(&count)
fmt.Printf("Count after inc: %d\n", count)
}Expected Output:
Initial Count: 41 Memory Address: [address] Count after inc: 42
How It Works: Step-by-Step
- Lines 6-8: increment dereferences valPtr and updates caller variable.
- Line 17: Passes address &count to function.
Key Concepts
- Go passes arguments by value; passing pointers allows functions to mutate caller state.
- Go does NOT allow pointer arithmetic (unlike C/C++), preventing memory buffer overflows.
- nil is the zero value for pointers.
Common Mistake: Dereferencing a nil pointer
Dereferencing a nil pointer causes a runtime panic.
❌ Incorrect
var p *int *p = 10 // Panic: runtime error: invalid memory address or nil pointer dereference
✅ Correct
val := 0; p := &val; *p = 10
Related Go Tutorials & Compiler
Go Multiple Return Values and Error Handling Signatures
Master Go signature multiple return values, named returns, and the idiomatic (result, error) convention without exceptions.
Go Methods and Receiver Functions: OOP Without Classes
Implement OOP methods in Go using value and pointer receivers on structs.
Go Goroutines, Channels, and sync.WaitGroup Concurrency
Master lightweight concurrency in Go using goroutines, channels (<-), and sync.WaitGroup.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.