Go 数组、slice、map

1. 数组

go中的数组需要提前定义好长度

  • 初始化 1
var course [3]string
course[0] = "go"
course[1] = "grpc"
course[2] = "gin"
  • 初始化 2
course := [3]string{"go", "grpc", "gin"}
  • 初始化 3

根据元素初始化长度

course := [...]string{"go", "grpc", "gin"}
  • 初始化 4
course := [3]string{1: "gin"}

这种指定索引的初始化,其他位置会为类型的零值
[ gin ]

  • 多维数组
var course [3][4]string
	course[0] = [4]string{"go", "gin", "grpc", "gogo"}
	course[1] = [4]string{"go", "gin", "grpc", "gogo"}
	course[2] = [4]string{"go", "gin", "grpc", "gogo"}

2. slice

  • append添加元素,常用
var course []string
course = append(course, "go")
course = append(course, "gin")
course = append(course, "grpc")
  • 从数组添加元素
allCourse := [3]string{"go","grpc","gin"}
course := allCourse[0:1]
  • make函数添加元素

make函数可以提前分配好slice的大小,避免slice频繁扩容,索引不可以超

course := make([]string, 3)
course[0] = "go"
  • 取值

前包后不包

course := make([]string, 3)
// 从0到1
fmt.Println(course[0:1])
// 头开始到1
fmt.Println(course[:1])
// 1开始到结束
fmt.Println(course[1:])
// 所有
fmt.Println(course[:])
  • 组合slice
course1 := []string{"go", "grpc"}
course2 := []string{"mysql", "redis", "mongodb"}
course1 = append(course1, course2...)
course1 = append(course1, course2[1: ]...)
  • 删除slice中元素(只能这样)
course1 := []string{"go", "grpc", "mysql", "redis", "mongodb"}
course1 = append(course1[:2], course1[3:]...)
  • 拷贝
course1 := []string{"go", "grpc"}
// 浅拷贝,复制内存地址
course2 := course1
// 浅拷贝,复制内存地址
course3 := course1[:]
// 深拷贝,复制值
course4 := make([]string, len(course1))
copy(course4, course1)
course1[0] = "更改"
fmt.Println(course1, course2, course3, course4)
// [更改 grpc] [更改 grpc] [更改 grpc] [go grpc]

3. map

  • 初始化

map定义之后必须初始化

map中最后一个值也要带逗号

map[key值类型]value值类型{}

course := map[string]string{
   "key1": "value1",
   "key2": "value2",
}

// 或
course := make(map[string]string, 3)
  • 添加
course["key3"] = "value3"
  • 遍历
for key, value := range course {
   fmt.Println(key, value)
}

for _, value := range course {
   fmt.Println(value)
}

for key := range course {
   fmt.Println(key)
}
  • 判断是否存在
value, ok := course["key11"]
if !ok {
   fmt.Println("不存在")
} else {
   fmt.Println("值" + value)
}

// 简写
if _, ok := course["key1"]; !ok {
    fmt.Println("不存在")
} else {
    fmt.Println("存在")
}
  • 删除元素
delete(course, "key1")
posted @ 2023-03-09 22:22  ForLivetoLearn  阅读(22)  评论(0编辑  收藏  举报