From efae6414db484e1c13ac265e3c347cd8fd49632e Mon Sep 17 00:00:00 2001 From: Inanc Gumus Date: Thu, 5 Sep 2019 23:27:51 +0300 Subject: [PATCH] add: explanations to decode to iface --- interfaces/11-decode-toiface/database.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/interfaces/11-decode-toiface/database.go b/interfaces/11-decode-toiface/database.go index f09209e..5b634c4 100644 --- a/interfaces/11-decode-toiface/database.go +++ b/interfaces/11-decode-toiface/database.go @@ -13,20 +13,26 @@ import ( "log" ) +// database is responsible for encoding and decoding a list. type database struct { list *list } func (db *database) UnmarshalJSON(data []byte) error { + // Provides a concrete data structure that we can use to decode. + // It is a slice of structs. var decodables []struct { - Type string - Item json.RawMessage + Type string // The product type. + Item json.RawMessage // The raw item data (from database.json) } + // First, decode the "Type" part. + // Leave the "Item" as raw json data. if err := json.Unmarshal(data, &decodables); err != nil { log.Fatalln(err) } + // Decode the "Item" part for each json object. for _, d := range decodables { it, err := db.newItem(d.Item, d.Type) if err != nil { @@ -39,7 +45,8 @@ func (db *database) UnmarshalJSON(data []byte) error { return nil } -func (db *database) newItem(data []byte, itemType string) (it item, _ error) { +// newItem decodes and returns a product type wrapped in an item iface value. +func (*database) newItem(data []byte, itemType string) (it item, _ error) { switch itemType { default: return nil, fmt.Errorf("newItem: type (%q) does not exist", itemType)