golang-map基本操作


map使用

声明和初始化

使用var只声明

  • // 只声明 var gMap map[string]string

使用var声明同时初始化

  • // 声明初始化 var hMap = map[string]string{"a": "b"}
package  main

import "fmt"

func main()  {
   var hMap map[string]string
   var XMap = map[string]string{"a": "b"}
   fmt.Println(hMap)
   fmt.Println(XMap)
   fmt.Printf("%T",hMap)
}

map字段的增删改查

package main

import "fmt"

func main() {
	m := make(map[string]string)
	//增
	m["app"] = "taobao"
	m["lang"] = "golang"
	//删
	delete(m, "app")
	fmt.Println(m)
	//改
	m["app"] = "jingdong"
	//单变量形式
    lang := m["lang"]
	fmt.Println(lang)
	fmt.Printf("%T\n", lang)
	//双变量形式
	lang1, exists := m["lang"]
	if exists {
		fmt.Printf("[lang存在 值: %v]\n", lang1)
	} else {
		fmt.Println("lang no ")
		m["lang"] = "java"
	}

}



map[lang:golang]
olang
string
[lang存在 值: golang]

Author: 千里
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source 千里 !
  TOC