Arrays, Slices and Maps are common data structures
(Array)
- The array is of fixed length.
- The length cannot be changed.
initialization
package main import ( "fmt" ) func main() { var scores [10]int scores[0] = 99 ("scoers:%d\n", scores) socres_english := [4]int{99, 100, 100, 99} for index, value := range socres_english { ("%d\t %d", index, value) } }
Starting: C:\Users\livingbody\go\bin\ 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. Slice
A slice is a lightweight structure that contains and represents a part of an array.
2.1 make create slices
# That is, create slices with length 10 and capacity 0score := make([]int, 0, 10)
- After slicing, you can assign values through append
- The slice can be resliced and then assigned through the index
- The slice will automatically increase after exceeding the capacity, and its own multiple
package main import ( "fmt" ) func main() { var scores [10]int scores[0] = 99 ("scoers:%d\n", scores) socres_english := [4]int{99, 100, 100, 99} for index, value := range socres_english { ("%d\t %d\n", index, value) } score_math := make([]int, 0, 10) score_math = append(score_math, 100) (score_math) (score_math[0]) score_math = score_math[0:8] score_math[7] = 99 (score_math) c := cap(score_math) (c) for i := 0; i < 25; i++ { score_math = append(score_math, i) if cap(score_math) != c { c = cap(score_math) (c) } } }
Output:
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 Map
It's like a hash table or dictionary in other languages. The way they work is to define keys and values, and the values in them can be retrieved, set and deleted.
Also created by the make method.
package main import ( "fmt" ) func main() { lookup := make(map[string]int) lookup["goku"] = 9001 power, exists := lookup["vegeta"] (power, exists) total := len(lookup) (total) delete(lookup, "goku") (len(lookup)) }
Starting: C:\Users\livingbody\go\bin\ 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
Iteration
for key, value := range lookup { ... }
Notice:
Map iterations have no order
This is the article about the detailed explanation of the use of arrays, slicing and mapping in Go language. For more related Go arrays, slices, and mapping content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!