Searching for Dictionary Elements
What happens when we search for an element in a dictionary that does not exist?
package main
import "fmt"
func main() {
m := map[string]int{
"shiyanlou": 0,
}
fmt.Print("The value of Windows is: ")
fmt.Println(m["Windows"])
}
The program output is as follows:
The value of Windows is: 0
We found that if the element does not exist in the dictionary, querying it will return the default value of the value type.
What about the key in the dictionary whose value is 0
?
package main
import "fmt"
func main() {
m := map[string]int{
"shiyanlou": 0,
}
fmt.Print("The value of Windows is: ")
fmt.Println(m["Windows"])
fmt.Print("The value of shiyanlou is: ")
fmt.Println(m["shiyanlou"])
}
The program output is as follows:
The value of Windows is: 0
The value of shiyanlou is: 0
We found that for a dictionary, the presentation of a value that does not exist and a value that exists but has a default value is the same.
This causes us a lot of confusion. How do we solve it?
As it turns out, the developers of Go had already thought of this issue. When we query an element in a dictionary, there will be one or two variable return values.
That is:
Windows, ok := m["Windows"]
Modify map.go
:
package main
import "fmt"
func main() {
m := map[string]int{
"shiyanlou": 0,
}
Windows, ok := m["Windows"]
fmt.Print("The value of Windows is: ")
fmt.Print(Windows)
fmt.Print(" Does it exist? ")
fmt.Println(ok)
shiyanlou, ok2 := m["shiyanlou"]
fmt.Print("The value of shiyanlou is: ")
fmt.Print(shiyanlou)
fmt.Print(" Does it exist? ")
fmt.Println(ok2)
}
The program output is as follows:
The value of Windows is: 0 Does it exist? false
The value of shiyanlou is: 0 Does it exist? true
Now, we can use the second return value of the query to determine whether the returned result is an existing initial default value or a nonexistent initial default value.