-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslice.go
More file actions
74 lines (60 loc) · 1.7 KB
/
slice.go
File metadata and controls
74 lines (60 loc) · 1.7 KB
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
package main
import "fmt"
func main() {
// create slice from array
var months = [...]string{
"Januari",
"Februari",
"Maret",
"April",
"Mei",
"Juni",
"Juli",
"Agustus",
"September",
"Oktober",
"November",
"Desember",
}
// get slice from array months index 4 to 7 (5th to 7th element)
var slice1 = months[4:7]
fmt.Println(slice1) // Mei, Juni, Juli
fmt.Println(len(slice1)) // length of slice
fmt.Println(cap(slice1)) // capacity of slice
//* modifying slice will also modify the underlying array
//months[5] = "Diubah"
//fmt.Println(slice1)
//slice1[0] = "Mei Lagi"
//fmt.Println(months)
// create slice from index 11 to the end
var slice2 = months[11:]
fmt.Println(slice2)
// append new value to the slice (will create a new array collection)
var slice3 = append(slice2, "Luthfi")
fmt.Println(slice3)
slice3[1] = "Bukan_Desember"
fmt.Println(slice3)
// will not affect the original array because the capacity is exceeded
fmt.Println(slice2)
fmt.Println(months)
// make function to create slice
// make([]Type, length, capacity)
newSlice := make([]string, 2, 5)
newSlice[0] = "Muhammad"
newSlice[1] = "Luthfi"
fmt.Println(newSlice)
fmt.Println(len(newSlice))
fmt.Println(cap(newSlice))
// copy slice
copySlice := make([]string, len(newSlice), cap(newSlice))
copy(copySlice, newSlice)
fmt.Println(copySlice)
// becareful when creating array and slice
// don't be confused between array and slice
// commonly developer golang use slice more than array because it's more flexible
// array has a fixed length, while slice can grow dynamically
iniArray := [5]int{1, 2, 3, 4, 5}
iniSlice := []int{1, 2, 3, 4, 5}
fmt.Println(iniArray)
fmt.Println(iniSlice)
}