golang map 的基本操作

文章目录

    定义并初始化

    例如,定义一个城市对应省份的 map

    cities := map[string]string {
        "烟台": "山东",
        "武汉": "湖北"
    }
    

    如何判断对其的键 key 不存在

    if province, ok := cities["烟台"]; ok {
        // 存在
    } else {
        // 不存在
    }
    

    注:

    • 存在时,ok 为 true
    • 不存在时,ok 为 false

    key 是 string, value 是 struct 的情况

    type WxConfig struct {
    	AppID  string
    	Secret string
    }
    
    var configs = map[string]WxConfig{
    	"stat": WxConfig{
    		AppID:  "",
    		Secret: "",
    	},
    }