From 1a27ab7bfb73cb424894f6808df464fc99b95f29 Mon Sep 17 00:00:00 2001 From: hoang Date: Thu, 21 May 2020 16:14:20 +0700 Subject: [PATCH] c1-m4-marshal a map --- c1-m4-activity/makejson.go | 39 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 c1-m4-activity/makejson.go diff --git a/c1-m4-activity/makejson.go b/c1-m4-activity/makejson.go new file mode 100644 index 0000000..227c80e --- /dev/null +++ b/c1-m4-activity/makejson.go @@ -0,0 +1,39 @@ +package main + +import ( + "encoding/json" + "fmt" +) + +var name, address string + +/** +* Zero value of a map: https://tour.golang.org/moretypes/19 +* A nil map has no keys, nor can keys be added. +* var addressBook map[string]string +**/ + +// AddressBook alias map type +type AddressBook map[string]string + +func main() { + // The make function returns a map of the given type, initialized and ready for use. + addressBook := make(AddressBook) + fmt.Printf("Please enter name: \n") + fmt.Scan(&name) + fmt.Printf("Please enter address: \n") + fmt.Scan(&address) + addressBook[name] = address + barr, err := json.Marshal(addressBook) + if err != nil { + fmt.Printf("Can't create json" + err.Error()) + } + fmt.Println("-----") + fmt.Printf("Original Object: %v\n", addressBook) + fmt.Printf("Json Object: %v\n", barr) + + // unmarshallAddressBook := make(AddressBook) + // err = json.Unmarshal(barr, &unmarshallAddressBook) + // fmt.Printf("Unmarshal Object: %v\n", unmarshallAddressBook) + fmt.Println("-----") +}