map数据结构

当您需要非常快速的键值查找时,映射是一种非常有用的数据结构。它们以极其多样化的方式使用,无论使用何种底层语言,它们都是任何程序员的宝贵工具。

dictHashMap

map基本语法

mapkeyvaluemake
makecapacity


// a map of string to int which has
// no set capacity
mymap := make(map[string]int)

// a map of bool to int which has a 
// set capacity of 2
boolmap := make(map[bool]int)

一旦我们初始化了map,您可以使用它们各自的值在map中设置键,如下所示:


mymap["mykey"] = 10
fmt.Println(mymap["mykey"]) // prints out 10

迭代键和值

rangekeysvaluesarrayslice:


for key, value := range mymap {
    fmt.Println(key)
    fmt.Println(value)
}
mymap
mapappend


var keyArray []string

for key := range mymap {
    keyArray = append(keyArray, key)
}

删除map中的元素

deletemap[key]delete


mymap["mykey"] = 1
fmt.Println(mymap["mykey"])
delete(mymap["mykey"])
fmt.Println("Value deleted from map")

将字符串映射到接口

stringinterface
UUIDinterfaceinterfaceUUID


package main

import "fmt"

type Service interface{
	SayHi()
}

type MyService struct{}
func (s MyService) SayHi() {
	fmt.Println("Hi")
}

type SecondService struct{}
func (s SecondService) SayHi() {
	fmt.Println("Hello From the 2nd Service")
}

func main() {
	fmt.Println("Go Maps Tutorial")
	// we can define a map of string uuids to
    // the interface type 'Service'
	interfaceMap := make(map[string]Service)
	
    // we can then populate our map with 
    // simple ids to particular services
	interfaceMap["SERVICE-ID-1"] = MyService{}
	interfaceMap["SERVICE-ID-2"] = SecondService{}

	// Incoming HTTP Request wants service 2
	// we can use the incoming uuid to lookup the required
	// service and call it's SayHi() method
	interfaceMap["SERVICE-ID-2"].SayHi()

}
SayHi()

$去运行main.go

Go Maps Tutorial
Hello From the 2nd Service
SayHi()


for key, service := range interfaceMap {
	fmt.Println(key)
	service.SayHi()
}
SayHi()

结论

希望你喜欢这个 Go map教程,它在某种程度上帮助了你!如果您有任何反馈或意见,那么我很乐意在下面的评论部分听到它们!