package main import ( "fmt" "sync" ) type Info struct { info map[int]string mu sync.RWMutex } func main() { x := &Info{info: make(map[int]string)} x.Set(1, "golang") s := x.Get(1) fmt.Println(s) } func (s *Info) Get(i int) string { s.mu.RLock() info := s.info[i] s.mu.RUnlock() return info } func (s *Info) Set(i int, name string) bool { s.mu.Lock() defer s.mu.Unlock() _, present := s.info[i] if present { return false } s.info[i] = name return true }
有疑问加站长微信联系(非本文作者)