Golang determines whether the specified key in the map exists

Release: 2019-12-31 09:17:43
Original
4212 people have browsed it

Golang determines whether the specified key in the map exists

Map is a built-in type in Go that binds keys and values ​​together. The corresponding value can be obtained by key.

A map can be created by passing the key and value types to the built-in function make. The syntax is: make(map[KeyType]ValueType).

Let's take a look at the method of judging whether the key in the map exists:

The judgment method is value,ok := map[key], if ok is true, it exists

package main
 
import "fmt"
 
func main() {
 
    demo := map[string]bool{
        "a": false,
    }
 
    //错误,a存在,但是返回false
    fmt.Println(demo["a"])
 
    //正确判断方法
    _, ok := demo["a"]
    fmt.Println(ok)
}
Copy after login

Output

false
true
Copy after login

For more golang knowledge, please pay attention to the golang tutorial column.

The above is the detailed content of Golang determines whether the specified key in the map exists. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!