package store import ( mystore "awesomeProject/store" factory "awesomeProject/store/factory" "errors" "sync" ) func init() { factory.Register("mem", &MemStore{ books: make(map[string]*mystore.Book), }) } type MemStore struct { sync.RWMutex books map[string]*mystore.Book } func (m *MemStore) Create(book *mystore.Book) error { if _, ok := m.books[book.Id]; ok { return errors.New("book is existed") } m.books[book.Id] = book return nil } func (m *MemStore) Update(book *mystore.Book) error { oldBook, ok := m.books[book.Id] if !ok { return errors.New("book not found") } oldBook.Name = book.Name oldBook.Authors = book.Authors oldBook.Press = book.Press return nil } func (m *MemStore) Get(s string) (mystore.Book, error) { oldBook, ok := m.books[s] if !ok { return mystore.Book{}, errors.New("book not found") } else { return *oldBook, nil } } func (m *MemStore) GetAll() ([]mystore.Book, error) { books := make([]mystore.Book, 0, len(m.books)) // 初始化切片,预分配容量 for _, book := range m.books { books = append(books, *book) // 解引用并添加到切片中 } return books, nil // 返回所有书籍 } func (m *MemStore) Delete(s string) error { if _, ok := m.books[s]; !ok { return errors.New("book not found") // 如果书籍未找到,返回错误 } delete(m.books, s) // 从 map 中删除书籍 return nil // 删除成功,返回 nil }