日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

詳解Go語言中數(shù)組,切片和映射的使用_Golang

作者:Livingbody ? 更新時間: 2022-09-04 編程語言

Arrays (數(shù)組), Slices (切片) 和 Maps (映射) 是常見的一類數(shù)據(jù)結(jié)構(gòu)

1.Arrays (數(shù)組)

  • 數(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", 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)建長度10,容量0的切片
score := make([]int, 0, 10)
  • 切片后可以通過append賦值
  • 切片可以重新切片,然后通過索引賦值
  • 切片超過容量會自動增大,自身倍數(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

就好比其他語言中的 hash 表或者字典。它們的工作方式就是:定義鍵和值,并且可以獲取,設(shè)置和刪除其中的值。

同樣通過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迭代沒有順序

原文鏈接:https://juejin.cn/post/7119383510036529159

欄目分類
最近更新