go-generics-cache icon indicating copy to clipboard operation
go-generics-cache copied to clipboard

Add a GetDefault method.

Open bn-jbowers opened this issue 1 year ago • 1 comments

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.

bn-jbowers avatar Sep 26 '23 15:09 bn-jbowers

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

Nikola-Milovic avatar Oct 07 '23 06:10 Nikola-Milovic

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 avatar Mar 05 '24 21:03 bn-jbowers

@bn-jbowers Thanks! I cherry-picked your commit at #49

Code-Hex avatar Apr 13 '24 10:04 Code-Hex