-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patharray.go
51 lines (39 loc) · 1.25 KB
/
array.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"fmt"
"strings"
)
func logArray(a []string) {
fmt.Printf("len = %d, cap = %d\n", len(a), cap(a))
// loop array by capacity with idx and val
for idx, val := range a {
fmt.Println(idx, val) // eg. 0 "a"
}
// loop array by capacity with only index
for idx := range a {
fmt.Println(idx, a[idx]) // eg. 0 "a"
}
// loop array by capacity with only val
for _, val := range a {
fmt.Println(val) // eg. "a"
}
}
func main() {
// Create array of string
a := []string{"a", "b", "c", "d", "e", "f"}
// Create new array with capacity = 8
b := make([]string, 8)
logArray(a) // len 6, cap 6
logArray(b) // len 8, cap 8, initial value is ""
// Slice array (extend length | drop elements),
// but capacity maybe keep without extended
logArray(a[:0]) // len 0, cap 6
logArray(a[:5]) // len 5, cap 6
logArray(a[1:]) // len 5, cap 5, drop 0th
logArray(a[2:5]) // len 3, cap 4, drop 0th, 1st, 5th, keep memory of the last elements
// Join array of elements to string
fmt.Println(strings.Join(a, ",")) // "a,b,c,d,e,f"
// Extend capacity of array
logArray(append(a, "g")) // append "g" to array, raise capacity if not enough
logArray(append(a, "g", "h", "i")) // append "g", "h", "i" to array, raise capacity if not enough
}