跳转到主要内容

在本教程中,我们将研究Go中的Map以及如何使用它们来统治世界!

我们将涵盖您需要了解的有关Map的所有内容,以便在您自己的 Go 应用程序中开始使用它们。我们将研究您在 Go 中与Map交互的所有各种方式,在本教程结束时,您将成为使用它们的大师。

Map数据结构


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

Go 中的 Map 可以被认为相当于 Python 中的 dict 或 Java 中的 HashMap。

Map基本语法


Go 中的映射可以使用 map 关键字后跟键类型和值类型来定义。这些类型可以是 Go 支持的任何基本类型,您可以在 Go 中使用获取Map类型的 make 关键字初始化新Map。

注意:make 内置函数需要一个可选的第二个容量参数,但是对于 Go 中的Map,这将被忽略,因为Map会自动增长和缩小

// 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


迭代键和值


在从 map 中检索值时,我们可以使用 range 关键字并像普通数组或切片一样循环键和值:

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


运行此命令将随后打印出此 mymap 映射中包含的所有键及其后续值。

如果您需要从给定映射中提取所有键,则可以使用此循环来检索所有键,然后将它们附加到键数组中。

var keyArray []string

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

删除Map中的元素


为了从Map中删除项目,我们可以使用内置的 delete 函数,该函数接受一个 map[key] 键,然后尝试从Map中删除给定的值。如果映射中不存在该键,则删除调用是无操作的,这实际上意味着它什么也不做。

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


将字符串映射到接口


Go 中的映射不仅可以用于将基本类型映射到基本类型。在更复杂的程序中,您可能需要映射字符串来表示接口。

例如,您想将传入的 HTTP 请求 UUID 映射到应用程序中的给定接口。这将允许您根据映射的 UUID 更改处理传入请求的接口。

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()

}

如果我们然后尝试运行它,我们应该看到我们已经成功地能够从这个Map中检索我们想要的服务,然后调用 SayHi() 方法。

$ go run main.go

Go Maps Tutorial
Hello From the 2nd Service


如果我们想变得更漂亮,我们可以遍历Map中的所有接口,就像我们在教程前面所做的那样,并调用每个 SayHi() 方法:

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


这将随后打印出服务密钥,然后调用它们各自的 SayHi() 方法。

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

文章链接