package bookstore import ( "errors" "fmt" ) type Category int const ( CategoryAutobiography Category = iota CategoryLargePrintRomance CategoryParticlePhysics ) var validCategory = map[Category]bool{ CategoryAutobiography: true, CategoryLargePrintRomance: true, CategoryParticlePhysics: true, } type Book struct { Title string Author string Copies int ID int PriceCents int DiscountPercents int category Category } type Catalog map[int]Book func Buy(b Book) (Book, error) { if b.Copies == 0 { return Book{}, errors.New("no copies left") } b.Copies -- return b, nil } func (c Catalog) GetAllBooks() []Book { result := []Book{} for _,b := range c { result = append(result, b) } return result } func (c Catalog) GetBook(ID int) (Book, error) { b, ok := c[ID] if !ok { return Book{}, fmt.Errorf("book with ID %d not found", ID) } return b, nil } func (b Book) NetPriceCents() int{ saving := b.PriceCents * b.DiscountPercents/100 return b.PriceCents - saving } func (b *Book) SetPriceCents(price int) (error) { if price < 0 { return fmt.Errorf("negative price %d", price) } b.PriceCents = price return nil } func (b *Book) SetCategory(category Category) error { if !validCategory[category] { return fmt.Errorf("unknown category %q", category) } b.category = category return nil } func (b Book) Category() Category { return b.category }