I think the documentation is incorrect.

Normally, weak pointers are used to break retain cycles in a system that uses 
references to implement garbage collection. Since Go has a tracing GC this 
isn’t necessary.

Usually, a “soft” reference, not a “weak” reference is used to implement 
caches. A “soft” reference being one that the GC can free if memory is needed 
and it is otherwise unreachable - but typically only releases it under memory 
pressure.

With a tracing GC, weak references are typically more useful for canonicalized 
maps - that is given a key you always want to return the same instance of the 
object, but if there are no longer any references to the object, the key (and 
value) can be removed from the map - which is sort of a cache, but not in the 
widely used sense.

With Go, implementing a LRU+ cache using standard references is typically all 
that is needed.

> On Apr 7, 2025, at 10:21 AM, Val Deleplace <deleplace2...@gmail.com> wrote:
> 
> "The primary use-cases for weak pointers <https://pkg.go.dev/weak#Pointer> 
> are for implementing caches"
> 
> I'm trying to create objects and insert a weak pointer to each of them in a 
> slice. The slice then contains the only reference to each object, thus it is 
> possible for each pointer's value to become nil anytime, and the objects' 
> memory garbage collected.
> 
> In practice, on my laptop (macOS, go 1.24.1) the weak pointers tend to become 
> nil very fast, before I'm finished inserting 400 objects in the slice, which 
> seems to be "as soon as the object becomes unreachable".  While this 
> observation is consistent with the documentation, I'm wondering how I can 
> effectively build a cache when the data tends to go away as soon as it is 
> inserted?
> 
> Here is my code <https://go.dev/play/p/mKxiOvI_IJh>, which behaves a bit 
> differently in the playground but the general observation remains.
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to golang-nuts+unsubscr...@googlegroups.com 
> <mailto:golang-nuts+unsubscr...@googlegroups.com>.
> To view this discussion visit 
> https://groups.google.com/d/msgid/golang-nuts/1a129699-ce4a-4deb-bb83-ea2fa484d83bn%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/golang-nuts/1a129699-ce4a-4deb-bb83-ea2fa484d83bn%40googlegroups.com?utm_medium=email&utm_source=footer>.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/615AD59F-5DE8-4D5B-85CF-122E2D4AC23C%40ix.netcom.com.

Reply via email to