go-generics-cache
go-generics-cache copied to clipboard
Add a GetDefault method.
This adds a GetDefault method, which will either return the value in the cache, or if it is not present, set it with the passed-in value, returning whichever value ends up in the cache.
This must be done inside the cache because calling .Get, then .Set if the value is not present, is a TOCTOU (Time Of Check to Time Of Use) problem; something else may have set that value in the meantime. Only the cache can perform this operation atomically and safely.
This seems like an useful functionality, (not a maintainer) but GetDefault
usually implies a helper function that just saves you from typing if res == nil...
. Would naming this GetSetDefault
(or something) be more clear on what it actually does? Since it also sets the value if mising
I kind of copied the terminology from Python here: https://www.geeksforgeeks.org/python-dictionary-setdefault-method/
I'm ambivalent about the naming. But I'm going to end up forking this internally now, since I need this. (For my use case it is concurrently-incorrect without this.)
@bn-jbowers Thanks! I cherry-picked your commit at #49