Project: Warehouse Inventory
The second project combines structs, maps, slices (and the slices package), errors, and interfaces, this time an interface you implement yourself.
A camping gear store keeps its goods in a warehouse. The starter code provides:
- The
Item{SKU, Nama, Kategori, Harga, Stok}struct (name, category, price, stock). - The
Gudang(warehouse) struct, which stores items in amap[string]Itemkeyed by SKU, along with theGudangBaruconstructor. - The sentinel errors
ErrSKUKosong,ErrSKUDuplikat,ErrTidakDitemukan,ErrStokKurang(empty SKU, duplicate SKU, not found, insufficient stock). - The
Diskon(discount) interface with a single method:Terapkan(total int) int.
Remember: a value you get from a map is a copy. To change an item's
Stok, take the item out of the map, change the field, then store it back.
Task
-
func (g *Gudang) Tambah(it Item) error- Empty SKU →
ErrSKUKosong. SKU already exists → an error that wrapsErrSKUDuplikat. - Otherwise, store the item in the map.
- Empty SKU →
-
func (g *Gudang) Jual(sku string, jumlah int) error- The SKU doesn't exist → an error that wraps
ErrTidakDitemukan. jumlahis more than the stock → an error that wrapsErrStokKurang(the stock doesn't change).- Otherwise, reduce the stock.
- The SKU doesn't exist → an error that wraps
-
func (g *Gudang) StokMenipis(batas int) []stringreturns the SKUs of every item withStok <= batas, sorted in ascending order (useslices.Sort, because map order is random). -
Implement the
Diskoninterface on the two types that are already declared:DiskonPersen{Persen int}→total - total*Persen/100.DiskonNominal{Potongan int}→total - Potongan, but never below 0.
-
func (g *Gudang) HitungTotal(keranjang map[string]int, d Diskon) (int, error)keranjang(the cart) maps SKU → quantity. The total is the sum ofHarga × jumlahfor each line.- A SKU that doesn't exist → an error that wraps
ErrTidakDitemukan. - If
disn'tnil, returnd.Terapkan(total); if it isnil, return the total as is. - This function does not change the stock.