-
Notifications
You must be signed in to change notification settings - Fork 153
/
21_slice_tricks.go
88 lines (78 loc) · 1.95 KB
/
21_slice_tricks.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"fmt"
"strconv"
)
func main() {
// Copy Slice
slice01 := []int{1, 2, 3, 4, 5}
copy01 := make([]int, len(slice01))
copy(copy01, slice01)
fmt.Println(copy01) // [1 2 3 4 5]
// PushFront
slice02 := []int{1, 2, 3, 4, 5}
copy02 := make([]int, len(slice02)+1)
copy02[0] = 10
copy(copy02[1:], slice02)
fmt.Println(copy02) // [10 1 2 3 4 5]
// PushFront
pushFront := func(s *[]int, elem int) {
temp := make([]int, len(*s)+1)
temp[0] = elem
copy(temp[1:], *s)
*s = temp
}
pushFront(©02, 100)
fmt.Println(copy02) // [100 10 1 2 3 4 5]
// PushBack
slice03 := []int{1, 2, 3, 4, 5}
slice03 = append(slice03, 10)
fmt.Println(slice03) // [1 2 3 4 5 10]
// PopFront
slice04 := []int{1, 2, 3, 4, 5}
slice04 = slice04[1:len(slice04):len(slice04)]
fmt.Println(slice04, len(slice04), cap(slice04)) // [2 3 4 5] 4 4
// PopBack
slice05 := []int{1, 2, 3, 4, 5}
slice05 = slice05[:len(slice05)-1 : len(slice05)-1]
fmt.Println(slice05, len(slice05), cap(slice05)) // [1 2 3 4] 4 4
// Delete
slice06 := []int{1, 2, 3, 4, 5}
copy(slice06[3:], slice06[4:])
slice06 = slice06[:len(slice06)-1 : len(slice06)-1]
fmt.Println(slice06, len(slice06), cap(slice06)) // [1 2 3 5] 4 4
make2DSlice := func(row, column int) [][]string {
mat := make([][]string, row)
// for i := 0; i < row; i++ {
for i := range mat {
mat[i] = make([]string, column)
}
return mat
}
mat := make2DSlice(3, 5)
for key, value := range mat {
fmt.Println(key, value)
}
/*
0 [ ]
1 [ ]
2 [ ]
*/
fmt.Println(mat[1], len(mat[1]), cap(mat[1])) // [ ] 5 5
// iterate over rows
for r := range mat {
// iterate over columns
for c := range mat[r] {
mat[r][c] = strconv.Itoa(r) + "x" + strconv.Itoa(c)
}
}
for key, value := range mat {
fmt.Println(key, value)
}
/*
0 [0x0 0x1 0x2 0x3 0x4]
1 [1x0 1x1 1x2 1x3 1x4]
2 [2x0 2x1 2x2 2x3 2x4]
*/
fmt.Println(mat[1], len(mat[1]), cap(mat[1])) // [1x0 1x1 1x2 1x3 1x4] 5 5
}