Rust book chapter 13: try introducing more generic parameters to increase the flexibility of the `Cacher` functionality

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:

Try modifying Cacher to hold a hash map rather than a single value. The keys of the hash map will be the arg values 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.value directly has a Some or a None value, the value function will look up the arg in the hash map and return the value if it’s present. If it’s not present, the Cacher will call the closure and save the resulting value in the hash map associated with its arg value.

The second problem with the current Cacher implementation is that it only accepts closures that take one parameter of type u32 and return a u32 . We might want to cache the results of closures that take a string slice and return usize values, for example. To fix this issue, try introducing more generic parameters to increase the flexibility of the Cacher functionality.

I gave it a go, and ended up with this code. But this will cause the argument of the closure function to be inferred as &{unknown} , is there any way to solve this other than manually marking the type?

Are you just concerned about what your editor is showing you? Your playground code compiles and passes the tests, so clearly rustc itself was able to figure it out.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.