栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang map 判断key是否存在

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

golang map 判断key是否存在

定义,赋值map
package main

import "fmt"

func main() {
    var countryCapitalMap map[string]string 
    countryCapitalMap = make(map[string]string)

    
    countryCapitalMap [ "France" ] = "巴黎"
    countryCapitalMap [ "Italy" ] = "罗马"
    countryCapitalMap [ "Japan" ] = "东京"
    countryCapitalMap [ "India " ] = "新德里"

    
    for country := range countryCapitalMap {
        fmt.Println(country, "首都是", countryCapitalMap [country])
    }

    
    capital, ok := countryCapitalMap [ "American" ] 
    
    
    if (ok) {
        fmt.Println("American 的首都是", capital)
    } else {
        fmt.Println("American 的首都不存在")
    }
}
判断key是否存在
if _, ok := map[key]; ok {
    // 存在
}
 
if _, ok := map[key]; !ok {
    // 不存在
}

判断方式为value,ok := map[key], ok为true则存在

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

输出

false
true

总结不易,如果对您有帮助,请一键三连,鼓励兔子发表更优秀的文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/909141.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号