詳解Go語(yǔ)言中數(shù)組,切片和映射的使用
Arrays (數(shù)組), Slices (切片) 和 Maps (映射) 是常見(jiàn)的一類數(shù)據(jù)結(jié)構(gòu)
1.Arrays (數(shù)組)
- 數(shù)組是定長(zhǎng)的。
- 長(zhǎng)度不可改變。
初始化
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.切片
切片是輕量的包含并表示數(shù)組的一部分的結(jié)構(gòu)。
2.1 make創(chuàng)建切片
# 即創(chuàng)建長(zhǎng)度10,容量0的切片 score := make([]int, 0, 10)
- 切片后可以通過(guò)append賦值
- 切片可以重新切片,然后通過(guò)索引賦值
- 切片超過(guò)容量會(huì)自動(dòng)增大,自身倍數(shù)
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
就好比其他語(yǔ)言中的 hash 表或者字典。它們的工作方式就是:定義鍵和值,并且可以獲取,設(shè)置和刪除其中的值。
同樣通過(guò)make方法創(chuàng)建。
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迭代沒(méi)有順序
到此這篇關(guān)于詳解Go語(yǔ)言中數(shù)組,切片和映射的使用的文章就介紹到這了,更多相關(guān)Go數(shù)組 切片 映射內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信