Pointers and Memory
Go has pointers like C (* and &), but they are designed to be safe. Pointers allow you to pass references to values, enabling you to modify the original data without copying it.
Pass-by-Reference
By default, Go copies arguments when passing them to functions. Use pointers to modify the original value instead of working with a copy.How It Works
&igets the memory address of variablei*intdeclares thatnumis a pointer to an integer*num = 20dereferences the pointer and modifies the original value
No Pointer Arithmetic
This safety feature prevents the buffer overflow bugs that plague C/C++ programs. While it limits low-level memory manipulation, it eliminates entire classes of security vulnerabilities.Why This Matters
In C/C++, you can increment a pointer to access adjacent memory:When to Use Pointers
1. Modifying Function Arguments
2. Avoiding Large Copies
When working with large structs, use pointers to avoid copying the entire structure:3. Nil Values
Pointers can benil, representing “no value”:
Memory Safety Guarantees
Go’s pointer safety comes from several restrictions:- No pointer arithmetic - Cannot increment or decrement pointers
- Garbage collection - Automatic memory management prevents dangling pointers
- No explicit deallocation - Cannot manually free memory (no
free()ordelete) - Type safety - Cannot cast arbitrary integers to pointers
Go’s garbage collector automatically frees memory when it’s no longer referenced, preventing memory leaks and dangling pointer bugs.