Sobes.tech
Middle+

Implement a cache based on map[string]any with a constructor, Get method, and Set method, considering concurrent access (Mutex)

sobes.tech AI

Answer from AI

go package cache

import "sync"

type Cache struct { mu sync.Mutex store map[string]any }

func NewCache() *Cache { return &Cache{ store: make(map[string]any), } }

func (c *Cache) Get(key string) (any, bool) { c.mu.Lock() defer c.mu.Unlock() val, ok := c.store[key] return val, ok }

func (c *Cache) Set(key string, value any) { c.mu.Lock() defer c.mu.Unlock() c.store[key] = value }


In this example, the Cache structure contains a map and a mutex to protect against concurrent access. The Get and Set methods lock the mutex during the operation to prevent data races.
Implement a cache based on map[string]any with a… - sobes.tech