课程: Advanced Go Programming: Data Structures, Code Architecture, and Testing

Introduction to the in-memory cache challenge

(electronic music) - [Presenter] This brings us to the third challenge. You'll be building a simple in-memory cache which will give us a great opportunity to practice everything you've learned so far. The cache will store and manage key value pairs. If a reader sends a key, then the cache will return the value corresponding to that key. If no key is found, then the cache should return a relevant message to the reader. The other side of the operation is writing values to the cache. If a writer sends a key value pair to the cache, then it will add it to the cache. If a value already exists for the given key, then the cache will overwrite the existing value with the new one provided by the writer. As always, I've written some code to get you started. First, we define a key and value type on line 16 and 17. These types can be modified, but we have set them as string types for the purposes of this challenge. Further down on lines 19 to 24, we define two interfaces. The value writer defines the set method and the value reader defines the get method. These two interfaces allow you to achieve small specialized interfaces. It also makes it possible for functions to choose what functionality they want access to. Your challenge is to implement the cache type, its constructor function, new cache, as well as its set and get methods. These are defined on lines 27 to 40. Further down, on lines 42 to 59, I have implemented some convenience functions which make testing our cache easier. The right values function takes slices of keys and values, then writes them to the cache one by one. The read values function takes in a list of keys and returns the corresponding values of those keys. You shouldn't change these functions, but feel free to have a look at how they've been implemented. Looking at the test code we create two slices of keys and values. Two keys, potato and banana, are repeated and should return their newest values only. In the rest of the test code, we write these keys and values, then read them again. Now have a go at implementing this fun challenge for yourself.

内容