Map
Before introducing Map, let us create an English-to-Chinese dictionary using Slice.
args := os.Args[1:]
if len(args) != 1 {
fmt.Println("Please enter an English word to translate into Chinese.")
return
}
userInput := args[0]
// Set up text mapping for English and Chinese.
eng := []string{
"Hi", "Welcome", "Sorry",
}
cht := []string{
"嗨", "歡迎", "抱歉",
}
for i, word := range eng {
if strings.ToLower(word) == strings.ToLower(userInput) {
fmt.Println(cht[i])
return
}
}
fmt.Println("Can't find the translated Chinese word.")
It works; however, the time complexity is O(n).
To handle this case, Go provides Map, which implements a hash table O(1).
Map Introduction
var dict map[string]string
1. The keyword 'map' indicates the 'Map' type.
2. The first 'string' represents the key type, which should be comparable in type.
It can be bool, int, string, or array which are comparable.
It cannot be slice or map.
3. The second 'string' represents the value type, which can be any type.
4. The zero value of map type is nil.
Ex:
var dict map[string]string
fmt.Printf("%#v\n", dict)
Result:
map[string]string(nil)
5. We can read a map without first initializing it, which allows us to avoid adding a condition to check if the map is nil before reading.
Ex:
var dict map[string]string
fmt.Printf("dict['exp']: %q\n", dict["exp"])
Result:
dict['exp']: ""
6. However, before we begin writing, we must first initiate the map.
Ex:
var dict map[string]string
dict["Hi"] = "嗨"
Error:
panic: assignment to entry in nil map
7. If the key does not exist in the map, Go returns the element type's zero value.
Ex:
dict := map[string]string{
"Hi": "嗨",
"Welcome": "歡迎",
}
value := dict["not found"]
fmt.Printf("dist['not found']: %q\n", value)
Result:
dict['not found']: ""
8. The following is the right technique to handle key not found instead of comparing the zero value of element type.
Ex:
dict := map[string]string{
"Hi": "嗨",
"Welcome": "歡迎",
"Empty": "",
}
if value, found := dict[query]; found {
fmt.Printf("dict[%q]: %q\n", query, value)
return
}
fmt.Printf("Key %q is not found\n", query)
Result:
// if query is "Empty"
dict["Empty"]: ""
// if query is "not found"
Key "not found" is not found
9. Key is unique. If the inserted key does not exist, go add the new key-value set; if the inserted key already exists, go will update the element at that key.
Ex:
dict := map[string]string{
"Hi": "嗨",
"Welcome": "歡迎",
}
dict["Hi"] = "嗨V2"
fmt.Printf("%#v\n", dict)
Result:
map[string]string{"Hi":"嗨V2", "Welcome":"歡迎"}
10. How can I delete a key-value pair?
Ex:
dict := map[string]string{
"Hi": "嗨",
"Welcome": "歡迎",
}
fmt.Printf("%#v\n", dict)
delete(dict, "Hi")
fmt.Printf("%#v\n", dict)
Result:
map[string]string{"Hi":"嗨", "Welcome":"歡迎"}
map[string]string{"Welcome":"歡迎"}
11. It is recommended NOT to iterate over a map because Map is not designed for it. We can use Slice instead.
In the end, let us rewrite the English-to-Chinese dictionary using Map.
args := os.Args[1:]
if len(args) != 1 {
fmt.Println("Please enter an English word to translate into Chinese.")
return
}
userInput := args[0]
// Set up text mapping for English and Chinese.
dict := map[string]string{
"Hi": "嗨",
"Welcome": "歡迎",
"Sorry": "抱歉",
}
if value, found := dict[userInput]; found {
fmt.Println(value)
return
}
fmt.Println("Can't find the translated Chinese word.")
No comments:
Post a Comment