数据类型:字典

字典

字典(Map 类型),是由若干个key:value这样的键值对映射组合在一起的数据结构

声明初始化字典

// 第一种方法
var scores map[string]int = map[string]int{"english": 80, "chinese": 85}

// 第二种方法
scores := map[string]int{"english": 80, "chinese": 85}

// 第三种方法
scores := make(map[string]int)
scores["english"] = 80
scores["chinese"] = 85
import "fmt"

func main() {
    //  先声明一个字典,key类型为string value类型为int
    var scores map[string]int

    //  只声明不赋值的map,零值为nil,此时不能给map赋值
    if scores == nil {
        // 需要使用 make 函数先对其初始化
        scores = make(map[string]int)
    }

    // 经过初始化后,就可以直接赋值
    scores["chinese"] = 92
    fmt.Println(scores)
}

字典的遍历

字典遍历提供了两种方式,一种是需要携带 value,另一种是只需要 key,需要使用 range 关键字

package main
 
import "fmt"
 
func main() {
   fruits := map[string]int{
      "apple":2,
      "banana":5,
      "orange":8,
   }
 
   // 需要携带 value
   for name,score := range fruits{
       fmt.Println(name, score)
   }
   // 只需要key
   for name := range fruits{
       fmt.Println(name)
   }
//只需读取value,用一个占位符
for _, score := range scores {
        fmt.Printf("value: %d\n", score)
    }
 
}

字典的相关操作

1.添加元素

scores["math"] = 95

2.更新元素 若key已存在,则直接更新value

scores["math"] = 100

3.读取元素 直接使用[key]即可 ,如果 key 不存在,也不报错,会返回其value-type 的零值 如: value的类型是int,key不存在时,就返回0

fmt.Println(scores["math"])

4.删除元素 使用 delete 函数,如果 key 不存在,delete 函数会静默处理,不会报错。

delete(scores, "math")

判断 key 是否存在

当key不存在,会返回value-type的零值 。 所以不能通过返回的结果是否是零值来判断对应的 key 是否存在,因为 key 对应的 value 值可能恰好就是零值。

字典的下标读取可以返回两个值,使用第二个返回值都表示对应的 key 是否存在,若存在ok为true,若不存在,则ok为false

import "fmt"

func main() {
    scores := map[string]int{"english": 80, "chinese": 85}
    math, ok := scores["math"]
    if ok {
        fmt.Printf("math 的值是: %d", math)
    } else {
        fmt.Println("math 不存在")
    }
}

Last updated

Was this helpful?