I have a method f that returns a Vec<usize> originally. Since f is expensive, is there a way to cache the result in a struct field, e.g. cached without &mut self? The equivalent Python code is
def f(self):
if self.cache is None:
self.cache = compute()
return self.cache
I'd probably put it behind some sort of Cache wrapper which stashes a copy of the arguments and return value in a HashMap and checks the HashMap before calling the function.
There are various ways you can change the implementation (using reference-counted pointers like Arc<[T]> instead of cloning the result/arguments, internal mutability/synchronisation, etc.), but here's a Playground snippet with the general idea: