When we talked about string interning earlier, we mentioned a concept that Go uses to implement its unique map feature: the “weak pointer.” We kind of breezed through it back then to stay on track with the main flow of that article.
If you haven’t checked that piece out yet, I’d highly recommend giving it a read: Inside Go’s Unique Package: String Interning Simplified. It’s one of those optimization tricks that makes VictoriaMetrics’ products faster. You can read it before or after this one—totally up to you.
A weak pointer is basically a way to reference a chunk of memory without locking it down, so the garbage collector can clean it up if no one else is actively holding onto it.
Well, yes, Go does have the weak pointer concept. It’s part of the weak package, which is tied pretty closely to the Go runtime. Interestingly, it used to be more of an internal tool, but recently there’s been a push to make it public through this proposal.
The key thing about weak pointers is that they’re safe. If the memory they’re pointing to gets cleaned up, the weak pointer automatically becomes nil — so there’s no risk of accidentally pointing to freed memory. And when you do need to hold onto that memory, you can convert a weak pointer into a strong one. That strong pointer tells the garbage collector, “Hey, hands off this memory while I’m using it.”