When Should You Use Pointers?
Pointers aren't something you need to use everywhere. Here's a practical guide.
Use a pointer if
- A function or method needs to change data that belongs to the caller. This is the most common reason, for example
func (k *Keranjang) Tambah(...). - The struct is large and often passed to functions. Copying an address (8 bytes) is cheaper than copying dozens of fields.
- You need to tell "not set" apart from the zero value. A
Diskon *intfield can benil(not set yet), which is different from0(set to zero). - The data has to be shared. For example
map[string]*Produk: every part of the program holds the same product, and its fields can be changed directly,gudang["A1"].Stok--, without the copy-change-store pattern.
You don't need a pointer if
- The type is small and isn't changed:
int,bool, a small struct likeTitik{X, Y}. - The type already behaves like a reference: maps, slices (for changing elements), channels, and functions. A pointer to a map (
*map[string]int) is almost never needed. - You want the data safe from accidental changes: value semantics means every function works on its own copy.
Returning a pointer from a function is safe
In some languages, returning the address of a local variable is a bug. In Go, it's safe: the compiler moves the variable to the heap when needed (escape analysis).
func ProdukBaru(nama string, harga int) *Produk {
p := Produk{Nama: nama, Harga: harga}
return &p // aman
}
Constructor functions named NewXxx or XxxBaru that return a pointer are a very common pattern in Go.
Try it yourself
The editor holds an example of map[string]*Produk and an optional *int field. Run it, then try changing the map type to map[string]Produk and see the compile error that appears on the line gudang["KPI-01"].Stok -= 3.