zoukankan      html  css  js  c++  java
  • go Map

    一、什么是map?

      map 是一种特殊的数据结构:一种元素对(pair)的无序集合,pair 的一个元素是 key,对应的另一个元素是 value,所以这个结构也称为关联数组或字典。这是一种快速寻找值的理想结构:给定 key,对应的 value 可以迅速定位。

    map 这种数据结构在其他编程语言中也称为字典(Python)

    二、概念

    map是引用类型,可以使用如下声明:

    var map1 map[keytype]valuetype
    var map1 map[string]int
    

      ([keytype] 和 valuetype 之间允许有空格,但是 gofmt 移除了空格)

    package main
    
    import "fmt"
    
    func main() {
    	var mapLit map[string]int
    	//var mapCreated map[string]float32
    	var mapAssigned map[string]int
    
    	mapLit = map[string]int{"one": 1, "two": 2}
    	mapCreated := make(map[string]float32) //mapCreated := map[string]float32{}
    	mapAssigned = mapLit
    
    	mapCreated["key1"] = 4.5
    	mapCreated["key2"] = 3.14159
    	mapAssigned["two"] = 3
    
    	fmt.Printf("Map literal at "one" is: %d
    ", mapLit["one"])
    	fmt.Printf("Map created at "key2" is: %f
    ", mapCreated["key2"])
    	fmt.Printf("Map assigned at "two" is: %d
    ", mapLit["two"])
    	fmt.Printf("Map literal at "ten" is: %d
    ", mapLit["ten"])
    }
    

      输出:

    Map literal at "one" is: 1
    Map created at "key2" is: 3.141590
    Map assigned at "two" is: 3
    Map literal at "ten" is: 0

    map 是 引用类型 的: 内存用 make 方法来分配。

    map 的初始化:

    var map1 = make(map[keytype] valuetype)。

    或者简写为:

    map1 := make(map[keytype] valuetype)。
    

    不要使用 new,永远用 make 来构造 map

    2.1map容量

    和数组不同,map 可以根据新增的 key-value 对动态的伸缩,因此它不存在固定长度或者最大限制。但是你也可以选择标明 map 的初始容量 capacity,就像这样:

    make(map[keytype]valuetype, cap)
    

      例如:

    map2 := make(map[string]float32, 100)
    

    三、判断是否在map中以及删除:

     

    package main
    import "fmt"
    
    func main() {
    	var value int
    	var isPresent bool
    
    	map1 := make(map[string]int)
    	map1["New Delhi"] = 55
    	map1["Beijing"] = 20
    	map1["Washington"] = 25
    	value, isPresent = map1["Beijing"]
    	if isPresent {
    		fmt.Printf("The value of "Beijing" in map1 is: %d
    ", value)
    	} else {
    		fmt.Printf("map1 does not contain Beijing")
    	}
    
    	value, isPresent = map1["Paris"]
    	fmt.Printf("Is "Paris" in map1 ?: %t
    ", isPresent)
    	fmt.Printf("Value is: %d
    ", value)
    
    	// delete an item:
    	delete(map1, "Washington")
    	value, isPresent = map1["Washington"]
    	if isPresent {
    		fmt.Printf("The value of "Washington" in map1 is: %d
    ", value)
    	} else {
    		fmt.Println("map1 does not contain Washington")
    	}
    }
    

      输出:

    The value of "Beijing" in map1 is: 20
    Is "Paris" in map1 ?: false
    Value is: 0
    map1 does not contain Washington

    四、map类型的切片:

    package main
    
    import "fmt"
    
    func main() {
    	// Version A:
    	items := make([]map[int]int, 5)
    	for i:= range items {
    		items[i] = make(map[int]int, 1)
    		items[i][1] = 2
    	}
    	fmt.Printf("Version A: Value of items: %v
    ", items)
    
    	// Version B: NOT GOOD!
    	items2 := make([]map[int]int, 5)
    	for _, item := range items2 {
    		item = make(map[int]int, 1) // item is only a copy of the slice element.
    		item[1] = 2 // This 'item' will be lost on the next iteration.
    	}
    	fmt.Printf("Version B: Value of items: %v
    ", items2)
    }
    

      输出:

    Version A: Value of items: [map[1:2] map[1:2] map[1:2] map[1:2] map[1:2]]
    Version B: Value of items: [map[] map[] map[] map[] map[]]

    需要注意的是,应当像 A 版本那样通过索引使用切片的 map 元素。在 B 版本中获得的项只是 map 值的一个拷贝而已,所以真正的 map 元素没有得到初始化。

    五、map排序

    // the telephone alphabet:
    package main
    import (
    	"fmt"
    	"sort"
    )
    
    var (
    	barVal = map[string]int{"alpha": 34, "bravo": 56, "charlie": 23,
    								"delta": 87, "echo": 56, "foxtrot": 12,
    								"golf": 34, "hotel": 16, "indio": 87,
    								"juliet": 65, "kili": 43, "lima": 98}
    )
    
    func main() {
    	fmt.Println("unsorted:")
    	for k, v := range barVal {
    		fmt.Printf("Key: %v, Value: %v / ", k, v)
    	}
    	keys := make([]string, len(barVal))
    	i := 0
    	for k, _ := range barVal {
    		keys[i] = k
    		i++
    	}
    	sort.Strings(keys)
    	fmt.Println()
    	fmt.Println("sorted:")
    	for _, k := range keys {
    		fmt.Printf("Key: %v, Value: %v / ", k, barVal[k])
    	}
    }
    

      输出:

    unsorted:
    Key: bravo, Value: 56 / Key: charlie, Value: 23 / Key: hotel, Value: 16 / Key: indio, Value: 87 / Key: kili, Value: 43 / Key: lima, Value: 98 / Key: alpha, Value: 34 / Key: delta, Value: 87 / Key: echo, Value: 56 / Key: foxtrot, Value: 12 / Key: golf, Value: 34 / Key: juliet, Value: 65 /
    sorted:
    Key: alpha, Value: 34 / Key: bravo, Value: 56 / Key: charlie, Value: 23 / Key: delta, Value: 87 / Key: echo, Value: 56 / Key: foxtrot, Value: 12 / Key: golf, Value: 34 / Key: hotel, Value: 16 / Key: indio, Value: 87 / Key: juliet, Value: 65 / Key: kili, Value: 43 / Key: lima, Value: 98 /

    但是如果你想要一个排序的列表你最好使用结构体切片,这样会更有效:

    type name struct {
    	key string
    	value int
    }
  • 相关阅读:
    Sublime Text shift+ctrl妙用(转载)
    编写一致的符合习惯的javascript
    Vue 部署单页应用,刷新页面 404/502 报错
    http 缓存策略浅析
    Vue 项目优化,持续更新...
    web安全之——XSS、CSRF
    javascript 易错知识点合集
    深入理解 js this 绑定机制
    javascript 模块依赖管理的本质
    VUE 项目刷新路由指向index.html
  • 原文地址:https://www.cnblogs.com/liubiaos/p/9371117.html
Copyright © 2011-2022 走看看