Get the latest tech news

Weak pointers in Go: why they matter now


Through the weak package, you can create these special pointers that automatically become nil when their target memory gets collected. While they’re a bit trickier to use than regular pointers, they’re super useful for things like canonicalization maps and memory-efficient caching. The implementation is pretty clever too, using an 8-byte indirection object to make garbage collection more efficient.

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. So, the main benefit of weak pointers is they let you tell the garbage collector, “Hey, it’s okay to get rid of this resource if no one’s using it — I can always recreate it later.” This works well for objects that take up significant memory but don’t need to stick around unless they’re actively being used. For example, in canonicalization maps — where you eliminate duplicates by keeping only one copy of each unique piece of data — you’re already saving a lot of memory by avoiding redundancy.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of Weak pointers

Weak pointers