Guest User

Untitled

a guest
Dec 19th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. package cache
  2.  
  3. import "fmt"
  4.  
  5. // Item represents an item within the cache
  6. type Item struct {
  7. Object interface{}
  8. }
  9.  
  10. // Cache represents the data structure for storing items in memory
  11. type Cache struct {
  12. items map[string]Item
  13. }
  14.  
  15. // New will create a new in memory KV store and return the address
  16. func New() *Cache {
  17. items := make(map[string]Item)
  18. c := &Cache{
  19. items: items,
  20. }
  21. return c
  22. }
  23.  
  24. // Put adds key with an value to the cache. Adding another element with the same key will overwrite the existing one.
  25. func (c *Cache) Put(key, value string) bool {
  26. item := Item{
  27. Object: value,
  28. }
  29. c.items[key] = item
  30. return true
  31. }
  32.  
  33. // Get returns a value for a given key. It returns nil if they key was not found.
  34. func (c *Cache) Get(key string) interface{} {
  35. item := c.items[key]
  36. return item.Object
  37. }
  38.  
  39. // Delete removes the key value pair for the provided key. The function does not return anything
  40. func (c *Cache) Delete(key string) {
  41. delete(c.items, key)
  42. }
  43.  
  44. // List will print the current list out on STDOUT
  45. func (c *Cache) List() {
  46. for key, element := range c.items {
  47. fmt.Printf("%s: %s\n", key, element.Object)
  48. }
  49. }
Add Comment
Please, Sign In to add comment