Apologies if what I'm asking has a completely obvious solution, but I just can't see it.
The Rust book section Limitations of the Cacher Implementation ends by saying this:
Cacherto hold a hash map rather than a single value. The keys of the hash map will be the
argvalues that are passed in, and the values of the hash map will be the result of calling the closure on that key. Instead of looking at whether
self.valuedirectly has a
valuefunction will look up the
argin the hash map and return the value if it’s present. If it’s not present, the
Cacherwill call the closure and save the resulting value in the hash map associated with its
The second problem with the current
Cacherimplementation is that it only accepts closures that take one parameter of type
u32and return a
u32. We might want to cache the results of closures that take a string slice and return
usizevalues, for example. To fix this issue, try introducing more generic parameters to increase the flexibility of the
I gave it a go, and ended up with this code. When I try to run it, I get errors to do with lifetimes, errors that at this point I have no idea how to fix or what their cause is. The test code seems all whacked up too, since I'm having to pass references to integer literals, but Cacher::value() doesn't seem like a function that should be taking ownership of its arguments. I seem to have gone into the weeds with the generics here, and so I'd appreciate a guide who could set me back on the right path.