Arrays (数组), Slices (切片) 和 Maps (映射) 是常见的一类数据结构
1.Arrays (数组)
- 数组是定长的。
- 长度不可改变。
初始化
package main
import (
"fmt"
)
func main() {
var scores [10]int
scores[0] = 99
fmt.Printf("scoers:%d\n", scores)
socres_english := [4]int{99, 100, 100, 99}
for index, value := range socres_english {
fmt.Printf("%d\t %d", index, value)
}
}
Starting: C:\Users\livingbody\go\bin\dlv.exe dap --check-go-version=false --listen=127.0.0.1:14487 from c:\Users\livingbody\goworkspace\hello
DAP server listening at: 127.0.0.1:14487
Type 'dlv help' for list of commands.
scoers:[99 0 0 0 0 0 0 0 0 0]
0 991 1002 1003 99
Process 14356 has exited with status 0
Detaching
dlv dap (15128) exited with code: 0
2.切片
切片是轻量的包含并表示数组的一部分的结构。
2.1 make创建切片
# 即创建长度10,容量0的切片
score := make([]int, 0, 10)
- 切片后可以通过append赋值
- 切片可以重新切片,然后通过索引赋值
- 切片超过容量会自动增大,自身倍数
package main
import (
"fmt"
)
func main() {
var scores [10]int
scores[0] = 99
fmt.Printf("scoers:%d\n", scores)
socres_english := [4]int{99, 100, 100, 99}
for index, value := range socres_english {
fmt.Printf("%d\t %d\n", index, value)
}
score_math := make([]int, 0, 10)
score_math = append(score_math, 100)
fmt.Println(score_math)
fmt.Println(score_math[0])
score_math = score_math[0:8]
score_math[7] = 99
fmt.Println(score_math)
c := cap(score_math)
fmt.Println(c)
for i := 0; i < 25; i++ {
score_math = append(score_math, i)
if cap(score_math) != c {
c = cap(score_math)
fmt.Println(c)
}
}
}
输出:
Type 'dlv help' for list of commands.
scoers:[99 0 0 0 0 0 0 0 0 0]
0 99
1 100
2 100
3 99
[100]
100
[100 0 0 0 0 0 0 99]
10
20
40
Process 20448 has exited with status 0
Detaching
dlv dap (7204) exited with code: 0
3.映射Map
就好比其他语言中的 hash 表或者字典。它们的工作方式就是:定义键和值,并且可以获取,设置和删除其中的值。
同样通过make方法创建。
package main
import (
"fmt"
)
func main() {
lookup := make(map[string]int)
lookup["goku"] = 9001
power, exists := lookup["vegeta"]
fmt.Println(power, exists)
total := len(lookup)
fmt.Println(total)
delete(lookup, "goku")
fmt.Println(len(lookup))
}
Starting: C:\Users\livingbody\go\bin\dlv.exe dap --check-go-version=false --listen=127.0.0.1:14812 from c:\Users\livingbody\goworkspace\hello
DAP server listening at: 127.0.0.1:14812
Type 'dlv help' for list of commands.
0 false
1
0
Process 924 has exited with status 0
Detaching
dlv dap (700) exited with code: 0
迭代
for key, value := range lookup {
...
}
注意:
map迭代没有顺序
到此这篇关于详解Go语言中数组,切片和映射的使用的文章就介绍到这了,更多相关Go数组 切片 映射内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!