refactor: map code

This commit is contained in:
Inanc Gumus
2019-05-04 20:35:25 +03:00
parent 46c1517467
commit 03c753fe56
4 changed files with 80 additions and 120 deletions

View File

@ -12,41 +12,41 @@ import (
) )
func main() { func main() {
/* // args := os.Args[1:]
#1: Nil Map: Read-Only // if len(args) != 1 {
*/ // fmt.Println("[english word] -> [turkish word]")
var dict map[string]string // return
fmt.Printf("Zero-value of a map: %#v\n", dict) // }
// query := args[0]
/* // #1: Nil Map: Read-Only
#5: You cannot assign to a nil map. var dict map[string]string
*/
// #5: You cannot assign to a nil map.
// dict["up"] = "yukarı" // dict["up"] = "yukarı"
// dict["down"] = "aşağı" // dict["down"] = "aşağı"
/* // #2: Map retrieval is O(1) — on average.
#2: Map retrieval is O(1) — on average.
*/
key := "good" key := "good"
//
// #4: you can use an uninitialized map without checking it is nil
//
// if dict != nil {
value := dict[key] value := dict[key]
fmt.Printf("%q means %#v\n", key, value) fmt.Printf("%q means %#v\n", key, value)
// #1B
fmt.Printf("# of Keys: %d\n", len(dict))
// fmt.Printf("Zero Value: %#v\n", dict)
// #4: Nil map ready to use
// if dict != nil {
// value := dict[key]
// fmt.Printf("%q means %#v\n", key, value)
// } // }
/* // #3: Cannot use non-comparable types as map key types
#3: Cannot use non-comparable types as map key types
*/
// var broken map[[]int]int // var broken map[[]int]int
// var broken map[map[int]string]bool // var broken map[map[int]string]bool
// //
// A map can only be compared to nil value // A map can only be compared to nil value
// _ = dict == nil // _ = dict == nil
/*
#1 Step 2
*/
fmt.Printf("The dictionary contains %d words.\n", len(dict))
} }

View File

@ -13,9 +13,7 @@ import (
) )
func main() { func main() {
/* // #2A: Get the key from CLI
#2—A: Get the key from CLI
*/
args := os.Args[1:] args := os.Args[1:]
if len(args) != 1 { if len(args) != 1 {
fmt.Println("[english word] -> [turkish word]") fmt.Println("[english word] -> [turkish word]")
@ -23,63 +21,35 @@ func main() {
} }
query := args[0] query := args[0]
/* // #1: Empty Map Literal
#1: Empty Map Literal
*/
// dict := map[string]string{} // dict := map[string]string{}
/* // 3: Map Literal
#3: Map Literal
Creates, initializes and returns a new map
with the given key-value pairs
*/
dict := map[string]string{ dict := map[string]string{
"good": "kötü", "good": "kötü",
"great": "harika", "great": "harika",
"perfect": "mükemmel", "perfect": "mükemmel",
/* // #4
#4: keys and values should be the same type
(key and value types do not need to be the same)
*/
// 42: "forty two", // 42: "forty two",
// "forty two": 42, // "forty two": 42,
} }
// you can only add new pairs to an initialized map
dict["up"] = "yukarı" // adds a new pair dict["up"] = "yukarı" // adds a new pair
dict["down"] = "aşağı" // adds a new pair dict["down"] = "aşağı" // adds a new pair
dict["good"] = "iyi" // #5: overwrites the value at the key: "good" dict["good"] = "iyi" // #5: overwrites the value at the key: "good"
dict["mistake"] = "" // #8: a key with a zero-value dict["mistake"] = "" // #8: a key with a zero-value
// you can query an uninitialized map for its length // #10: comma ok in a short if
fmt.Printf("The dictionary contains %d words.\n", len(dict)) if value, ok := dict[query]; ok {
fmt.Printf("%q means %#v\n", query, value)
return
}
fmt.Printf("%q not found.\n", query)
/* // fmt.Printf("Zero Value: %#v\n", dict)
#6: getting values from a map using keys directly fmt.Printf("# of Keys : %d\n", len(dict))
*/
// fmt.Println("good -> ", dict["good"])
// fmt.Println("great -> ", dict["great"])
// fmt.Println("perfect -> ", dict["perfect"])
/* // #13: compare a map using its printed output
#11: looping over a map might be a sign of a design mistake
in your software.
(it prints unordered output)
*/
// for k, v := range dict {
// fmt.Printf("%q means %#v\n", k, v)
// }
/*
#12: printing a map (ordered output since Go 1.12)
*/
// fmt.Printf("%#v\n", dict)
/*
#13: compare a map using its printed output
(handy when testing)
*/
// copied := map[string]string{"up": "yukarı", "down": "aşağı", // copied := map[string]string{"up": "yukarı", "down": "aşağı",
// "mistake": "", "good": "iyi", "great": "harika", // "mistake": "", "good": "iyi", "great": "harika",
// "perfect": "mükemmel"} // "perfect": "mükemmel"}
@ -91,29 +61,31 @@ func main() {
// fmt.Println("Maps are equal") // fmt.Println("Maps are equal")
// } // }
/* // #12: printing a map (ordered output since Go 1.12)
#2—B: retrieve values by key - O(1) efficiency // fmt.Printf("%#v\n", dict)
(even from an uninitialized map)
*/ // #11
// for k, v := range dict {
// fmt.Printf("%q means %#v\n", k, v)
// }
// #9: check for non-existing key: with comma, ok
// value, ok := dict[query]
// if !ok {
// fmt.Printf("%q not found.\n", query)
// }
// #7: check for non-existing key using zero-value
// if value == "" {
// fmt.Printf("%q not found.\n", query)
// }
// #6: getting values from a map using keys directly
// fmt.Println("good -> ", dict["good"])
// fmt.Println("great -> ", dict["great"])
// fmt.Println("perfect -> ", dict["perfect"])
// #2B: retrieve values by key - O(1) efficiency
// value := dict[query] // value := dict[query]
/*
#7: check for non-existing key using zero-value
*/
// if value == "" {}
/*
#9: check for non-existing key: with comma, ok
*/
// value, ok := dict[query]
// if !ok {}
/*
#10: comma ok in a short if
*/
if value, ok := dict[query]; ok {
fmt.Printf("%q means %#v\n", query, value)
return
}
fmt.Printf("%q not found.\n", query)
} }

View File

@ -24,45 +24,29 @@ func main() {
"good": "iyi", "good": "iyi",
"great": "harika", "great": "harika",
"perfect": "mükemmel", "perfect": "mükemmel",
"awesome": "mükemmel", // #5
// #5: this overwrites the mükemmel in the turkish map
"awesome": "mükemmel",
} }
// #1: map value is a pointer to a real map in the memory // turkish := dict // #1
// turkish := dict
// turkish["good"] = "güzel" // turkish["good"] = "güzel"
// dict["great"] = "kusursuz" // dict["great"] = "kusursuz"
// #6: delete can delete a pair from a map delete(dict, "awesome") // #6
delete(dict, "awesome") delete(dict, "awesome") // #7: no-op
// #7: no-op
delete(dict, "awesome")
delete(dict, "notexisting") delete(dict, "notexisting")
// #8: destroying a map completely (false) // dict = nil // #8
// dict = nil for k := range dict { // #9
// #9: destroying a map completely (true)
// replaces the whole loop with a single instruction:
// "call runtime.mapclear()"
for k := range dict {
delete(dict, k) delete(dict, k)
} }
// #2: make initializes a new map value and returns a pointer to it // turkish := make(map[string]string) // #2
// turkish := make(map[string]string) turkish := make(map[string]string, len(dict)) // #3
// #3: make(T, hint) => hint is an advice for initing a large enough map
turkish := make(map[string]string, len(dict))
for k, v := range dict { for k, v := range dict {
turkish[v] = k turkish[v] = k
} }
// #4: add turkish dictionary // fmt.Printf("english: %q\nturkish: %q\n", dict, turkish) // #4
// fmt.Printf("english: %q\nturkish: %q\n", dict, turkish)
if value, ok := dict[query]; ok { if value, ok := dict[query]; ok {
fmt.Printf("%q means %#v\n", query, value) fmt.Printf("%q means %#v\n", query, value)
return return

View File

@ -10,20 +10,24 @@ package main
import "fmt" import "fmt"
func main() { func main() {
// let's create a slice of coders.
coders := []string{"pike", "thompson", "lovelace", "knuth"} coders := []string{"pike", "thompson", "lovelace", "knuth"}
// let's create a map for tracking whether they are gophers or not.
gophers := make(map[string]bool, len(coders)) gophers := make(map[string]bool, len(coders))
// let's mark the gophers
gophers["thompson"] = true gophers["thompson"] = true
gophers["pike"] = true gophers["pike"] = true
fmt.Println(gophers["pike"]) fmt.Println(gophers["pike"])
fmt.Println(gophers["lovelace"]) fmt.Println(gophers["lovelace"])
if _, ok := gophers["pike"]; ok { // unnecessary
// if _, ok := gophers["pike"]; ok {
// fmt.Println("pike is a gopher")
// } else {
// fmt.Println("pike is NOT a gopher")
// }
// easier
if gophers["pike"] {
fmt.Println("pike is a gopher") fmt.Println("pike is a gopher")
} else { } else {
fmt.Println("pike is NOT a gopher") fmt.Println("pike is NOT a gopher")