码迷,mamicode.com
首页 > 其他好文 > 详细

go map数据结构

时间:2017-08-29 11:02:46      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:技术分享   range   value   bsp   nbsp   abc   map   microsoft   ges   

map数据结构

key-value的数据结构,又叫字典或关联数组

  • 声明:
var map1 map[keytype]valuetype
var a map[string]string
var a map[string]int
var a map[int]string
var a map[string]map[string]string

备注:声明是不会分配内存的,初始化需要make

样例一:

func testMap() {
	var a map[string]string
        a = make(map[string]string, 10)
	a["abc"] = "efg"
	a["abc"] = "efg"
	a["abc1"] = "efg"
	fmt.Println(a)
}

样例二:

func testMap() {
        a := make(map[string]string, 10)
	a["abc"] = "efg"
	a["abc"] = "efg"
	a["abc1"] = "efg"
	fmt.Println(a)
}

样例三:

func testMap() {
	var a map[string]string = map[string]string{
		"key": "value",
	}
	a["abc"] = "efg"
	a["abc"] = "efg"
	a["abc1"] = "efg"
	fmt.Println(a)
}

技术分享

 

  • map相关操作
var a map[string]string = map[string]string{“hello”: “world”}
a = make(map[string]string, 10)

插入和更新:a[“hello”] = “world”

查找:Val, ok := a[“hello”]

遍历:

for k, v := range a { 
    fmt.Println(k,v) 
}

删除:delete(a, “hello”)

长度:len(a)

func trans(a map[string]map[string]string) {
	for k, v := range a {
		fmt.Println(k)
		for k1, v1 := range v {
			fmt.Println("\t", k1, v1)
		}
	}
}

func testMap4() {
	a := make(map[string]map[string]string, 100)
	a["key1"] = make(map[string]string)
	a["key1"]["key2"] = "abc"
	a["key1"]["key3"] = "abc"
	a["key1"]["key4"] = "abc"
	a["key1"]["key5"] = "abc"

	a["key2"] = make(map[string]string)
	a["key2"]["key2"] = "abc"
	a["key2"]["key3"] = "abc"

	trans(a)
	delete(a, "key1")
	fmt.Println()
	trans(a)
	fmt.Println(len(a))
}

 

  • 多层map
func testMap2() {
	a := make(map[string]map[string]string, 100)
	a["key1"] = make(map[string]string)
	a["key1"]["key2"] = "abc"
	a["key1"]["key3"] = "abc"
	a["key1"]["key4"] = "abc"
	a["key1"]["key5"] = "abc"
	fmt.Println(a)
}

技术分享

 

  • slice of map
func testMap5() {
	var a []map[int]int
	a = make([]map[int]int, 5)

	if a[0] == nil {
		a[0] = make(map[int]int)
	}
	a[0][10] = 10
	fmt.Println(a)
}

技术分享

 

go map数据结构

标签:技术分享   range   value   bsp   nbsp   abc   map   microsoft   ges   

原文地址:http://www.cnblogs.com/shhnwangjian/p/7446995.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!