课程: Advanced Go Programming: Data Structures, Code Architecture, and Testing
Solution: In-memory cache - Go教程
课程: Advanced Go Programming: Data Structures, Code Architecture, and Testing
Solution: In-memory cache
(upbeat music) - [Instructor] I hope you had fun experimenting and implementing this challenge. Let's have a look at my solution for the in-memory cache. On lines 27 to 30, I've made some changes to our Cache custom type by adding a values map using the key and value types defined on lines 16 and 17. I've also added a ReadWriteMutex to the cache in order to make it safe for concurrent usage. On line 34, I modified the implementation of the new cache function to initialize the values map. We don't need to initialize the ReadWriteMutex because the zero values of the locks in the sync package are ready for use. On lines 38 to 42, I implemented the set method and began by acquiring the cache lock. Then immediately deferring the unlock. Since this method will write to the values map, I acquired the full lock. Then on line 41, I wrote the new value together with its corresponding key. The values map will take care of value overwriting, ensuring that only the newest values are saved. Further down on lines 44 to 54, I implemented the get method. In the same way as before, I begin by acquiring the lock and immediately deferring the unlock. This method only requires a read lock since the get method will not be writing values. On line 48, I read the value of the corresponding key along with the optional Boolean that indicates whether this is an existing value. On lines 49 to 51, I return an error in the case that a value is not found. This will return an empty value and an error. An alternative signature for the cache get method would be to return a Boolean as the second return value instead of an error. However, I have opted to use an error because it's more intuitive to use them. Finally, on line 53, I returned the retrieved value and the nil error. I've made no changes to the write values and read values functions on lines 56 to 73. One thing to notice is that these functions make use of the defined ValueWriter and ValueReader interfaces to ensure that the correct functionality is available while not becoming tightly coupled with the cache concrete type. Let's run our solution using the Test My Code button. The code returns as expected. You can see from the output that the retrieved keys potato and banana only had their latest values retrieved regardless of being read twice. This has been a great exploration of the use and power of interfaces for writing robust code.
随堂练习,边学边练
下载课堂讲义。学练结合,紧跟进度,轻松巩固知识。