Intern — Junior
Have you used caching mechanisms in your projects?
sobes.tech AI
Answer from AI
Yes, caching is often used in Go projects to improve performance and reduce load on external resources.
For example, built-in data structures like map can be used for simple in-memory caching, or third-party libraries such as golang-lru or groupcache.
Here's an example of a simple cache using a map and mutex for thread safety:
package main
import (
"fmt"
"sync"
)
type Cache struct {
mu sync.Mutex
store map[string]string
}
func NewCache() *Cache {
return &Cache{store: make(map[string]string)}
}
func (c *Cache) Get(key string) (string, bool) {
c.mu.Lock()
defer c.mu.Unlock()
val, ok := c.store[key]
return val, ok
}
func (c *Cache) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.store[key] = value
}
func main() {
cache := NewCache()
cache.Set("foo", "bar")
if val, ok := cache.Get("foo"); ok {
fmt.Println("Cached value:", val)
} else {
fmt.Println("Value not found in cache")
}
}
This approach helps quickly return frequently requested data without repeated calculations or database calls.