Exercises & activities from the go workshop provided by Packt: https://courses.packtpub.com/courses/go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
867 B

  1. package main
  2. import "fmt"
  3. const GlobalLimit = 100
  4. const MaxCacheSize = 10 * GlobalLimit
  5. const (
  6. CacheKeyBook = "book_"
  7. CacheKeyCD = "cd_"
  8. )
  9. var cache map[string]string
  10. func cacheGet(key string) string {
  11. return cache[key]
  12. }
  13. func cacheSet(key, val string) {
  14. if len(cache)+1 >= MaxCacheSize {
  15. return
  16. }
  17. cache[key] = val
  18. }
  19. func getBook(isbn string) string {
  20. return cacheGet(CacheKeyBook + isbn)
  21. }
  22. func setBook(isbn, name string) {
  23. cacheSet(CacheKeyBook+isbn, name)
  24. }
  25. func getCD(sku string) string {
  26. return cacheGet(CacheKeyCD + sku)
  27. }
  28. func setCD(sku, title string) {
  29. cacheSet(CacheKeyCD+sku, title)
  30. }
  31. func main() {
  32. cache = make(map[string]string)
  33. setBook("1234-5678", "Get ready to Go")
  34. setCD("1234-5678", "Get ready to Go audio book")
  35. fmt.Println("Book:", getBook("1234-5678"))
  36. fmt.Println("CD :", getCD("1234-5678"))
  37. }