Created
December 19, 2018 11:11
-
-
Save pxlpnk/5ea3831e59c5fe8bb176b1f588150ce5 to your computer and use it in GitHub Desktop.
A super simple key ValueStore to practise some golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package cache | |
import "fmt" | |
// Item represents an item within the cache | |
type Item struct { | |
Object interface{} | |
} | |
// Cache represents the data structure for storing items in memory | |
type Cache struct { | |
items map[string]Item | |
} | |
// New will create a new in memory KV store and return the address | |
func New() *Cache { | |
items := make(map[string]Item) | |
c := &Cache{ | |
items: items, | |
} | |
return c | |
} | |
// Put adds key with an value to the cache. Adding another element with the same key will overwrite the existing one. | |
func (c *Cache) Put(key, value string) bool { | |
item := Item{ | |
Object: value, | |
} | |
c.items[key] = item | |
return true | |
} | |
// Get returns a value for a given key. It returns nil if they key was not found. | |
func (c *Cache) Get(key string) interface{} { | |
item := c.items[key] | |
return item.Object | |
} | |
// Delete removes the key value pair for the provided key. The function does not return anything | |
func (c *Cache) Delete(key string) { | |
delete(c.items, key) | |
} | |
// List will print the current list out on STDOUT | |
func (c *Cache) List() { | |
for key, element := range c.items { | |
fmt.Printf("%s: %s\n", key, element.Object) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment