Go语言的map

什么是map

map 是在 Go 中将值(value)与键(key)关联的内置类型。通过相应的键可以获取到值。类似与Python中的字典。

如何创建map

通过向 make 函数传入键和值的类型,可以创建 mapmake(map[type of key]type of value) 是创建 map 的语法。

personSalary := make(map[string]int)

上面的代码创建了一个名为 personSalary 的 map,其中键是 string 类型,而值是 int 类型。

map 的零值是 nil。如果你想添加元素到 nil map 中,会触发运行时 panic。因此 map 必须使用 make 函数初始化。

package main

import (
    "fmt"
)

func main() {  
    var personSalary map[string]int
    if personSalary == nil {
        fmt.Println("map is nil. Going to make one.")
        personSalary = make(map[string]int)
    }
}

上面的程序中,personSalary 是 nil,因此需要使用 make 方法初始化,程序将输出 map is nil. Going to make one.

给 map 添加元素

给 map 添加新元素的语法和数组相同。下面的程序给 personSalary map 添加了几个新元素。

package main

import (
    "fmt"
)

func main() {
    personSalary := make(map[string]int)
    personSalary["steve"] = 12000
    personSalary["jamie"] = 15000
    personSalary["mike"] = 9000
    fmt.Println("personSalary map contents:", personSalary)
}

上面的程序输出:personSalary map contents: map[steve:12000 jamie:15000 mike:9000]
你也可以在声明的时候初始化 map。

package main

import (  
    "fmt"
)

func main() {  
    personSalary := map[string]int {
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("personSalary map contents:", personSalary)
}

上面的程序声明了 personSalary,并在声明的同时添加两个元素。之后又添加了键 mike。程序输出:

personSalary map contents: map[steve:12000 jamie:15000 mike:9000]

键不一定只能是 string 类型。所有可比较的类型,如 boolean,interger,float,complex,string 等,都可以作为键。

获取 map 中的元素

目前我们已经给 map 添加了几个元素,现在学习下如何获取它们。获取 map 元素的语法是 map[key]

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    employee := "jamie"
    fmt.Println("Salary of", employee, "is", personSalary[employee])
}

上面的程序很简单。获取并打印员工 jamie 的薪资。程序输出 Salary of jamie is 15000

如果获取一个不存在的元素,会发生什么呢?map 会返回该元素类型的零值。在 personSalary 这个 map 里,如果我们获取一个不存在的元素,会返回 int 类型的零值 0

package main

import (  
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    employee := "jamie"
    fmt.Println("Salary of", employee, "is", personSalary[employee])
    fmt.Println("Salary of joe is", personSalary["joe"])
}

上面程序输出:

Salary of jamie is 15000
Salary of joe is 0

上面程序返回 joe 的薪资是 0personSalary 中不包含 joe 的情况下我们不会获取到任何运行时错误。

如果我们想知道 map 中到底是不是存在这个 key,该怎么做:

value, ok := map[key]

上面就是获取 map 中某个 key 是否存在的语法。如果 oktrue,表示 key 存在,key 对应的值就是 value ,反之表示 key 不存在。

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    newEmp := "joe"
    value, ok := personSalary[newEmp]
    if ok == true {
        fmt.Println("Salary of", newEmp, "is", value)
    } else {
        fmt.Println(newEmp,"not found")
    }
}

上面的程序中,第 15 行,joe 不存在,所以 okfalse。程序将输出:

joe not found

遍历 map 中所有的元素需要用 for range 循环。

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("All items of a map")
    for key, value := range personSalary {
        fmt.Printf("personSalary[%s] = %d\n", key, value)
    }

}

上面程序输出:

All items of a map
personSalary[mike] = 9000
personSalary[steve] = 12000
personSalary[jamie] = 15000

有一点很重要,当使用 for range 遍历 map 时,不保证每次执行程序获取的元素顺序相同。

删除 map 中的元素

删除 map 中 key 的语法是 delete(map, key)。这个函数没有返回值。

package main

import (  
    "fmt"
)

func main() {  
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("map before deletion", personSalary)
    delete(personSalary, "steve")
    fmt.Println("map after deletion", personSalary)

}

上述程序删除了键 “steve”,输出:

map before deletion map[steve:12000 jamie:15000 mike:9000]
map after deletion map[mike:9000 jamie:15000]

获取 map 的长度

获取 map 的长度使用 len 函数。

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("length is", len(personSalary))
}

上述程序中的 len(personSalary) 函数获取了 map 的长度。程序输出 length is 3

Map 是引用类型

slices 类似,map 也是引用类型。当 map 被赋值为一个新变量的时候,它们指向同一个内部数据结构。因此,改变其中一个变量,就会影响到另一变量。

package main

import (
    "fmt"
)

func main() {
    personSalary := map[string]int{
        "steve": 12000,
        "jamie": 15000,
    }
    personSalary["mike"] = 9000
    fmt.Println("Original person salary", personSalary)
    newPersonSalary := personSalary
    newPersonSalary["mike"] = 18000
    fmt.Println("Person salary changed", personSalary)
}

上面程序中的第 14 行,personSalary 被赋值给 newPersonSalary。下一行 ,newPersonSalarymike 的薪资变成了 18000personSalaryMike 的薪资也会变成 18000。程序输出:

Original person salary map[steve:12000 jamie:15000 mike:9000]
Person salary changed map[steve:12000 jamie:15000 mike:18000]

当 map 作为函数参数传递时也会发生同样的情况。函数中对 map 的任何修改,对于外部的调用都是可见的。

Map 的相等性

map 之间不能使用 == 操作符判断,== 只能用来检查 map 是否为 nil

package main

func main() {
    map1 := map[string]int{
        "one": 1,
        "two": 2,
    }

    map2 := map1

    if map1 == map2 {
    }
}

上面程序抛出编译错误 invalid operation: map1 == map2 (map can only be compared to nil)
判断两个 map 是否相等的方法是遍历比较两个 map 中的每个元素。

Go语言中,可以使用以下方式来查找map中的值: ```go val, ok := mapName\[key\] ``` 其中,`mapName`是你定义的map变量的名称,`key`是你要查找的键值。这个语法会返回两个值,`val`是对应键值的值,`ok`是一个布尔值,表示是否找到了对应的键值。如果找到了,`ok`的值为`true`,否则为`false`。 下面是一个示例代码: ```go package main import "fmt" func main() { cities := make(map\[string\]string) cities\["no1"\] = "北京" cities\["no2"\] = "上海" cities\["no3"\] = "广州" val, ok := cities\["no2"\] if ok { fmt.Printf("找到了,值为%v\n", val) // 输出:找到了,值为上海 } else { fmt.Println("没有找到") } } ``` 在这个示例中,我们定义了一个名为`cities`的map变量,并给它赋值。然后,我们使用`cities\["no2"\]`来查找键为`"no2"`的值。由于存在这个键,所以`ok`的值为`true`,并且将对应的值`"上海"`赋给了`val`。最后,我们根据`ok`的值来判断是否找到了对应的值,并进行相应的输出。 希望这个例子能够帮助你理解如何在Go语言中查找map的值。 #### 引用[.reference_title] - *1* *2* *3* [golang语言 map全方位介绍 【图文+代码】](https://blog.csdn.net/qq_45615577/article/details/122325035)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值