-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09_slices.go
More file actions
58 lines (47 loc) · 1.19 KB
/
09_slices.go
File metadata and controls
58 lines (47 loc) · 1.19 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
package gobyexample
import "fmt"
// WorkWithSlices - Create slices and print them to stdout
func WorkWithSlices() {
// create zero-valued empty slice with built-in make function
s := make([]string, 3)
fmt.Println("emp:", s)
// get and set a slice
s[0] = "a"
s[1] = "b"
s[2] = "c"
fmt.Println("set:", s)
fmt.Println("get:", s[2])
// get length of a slice
fmt.Println("len:", len(s))
// the built-in function `append` returns a slice
// containing one or more new values
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println("apd:", s)
// copy a slice
c := make([]string, len(s))
copy(c, s)
fmt.Println("cpy:", c)
// slice operator - from index 2 up to 5, excluding 5
l := s[2:5]
fmt.Println("sl1:", l)
// slice up to (but excluding) s[5]
l = s[:5]
fmt.Println("sl2:", l)
// slice up from (and including) s[2]
l = s[2:]
fmt.Println("sl3:", l)
// declare and initalize a variable for a slice in one line
t := []string{"g", "h", "i"}
fmt.Println("dcl:", t)
// multi-dimensional slice
twoD := make([][]int, 3)
for i := 0; i < 3; i++ {
innerLen := i + 1
twoD[i] = make([]int, innerLen)
for j := 0; j < innerLen; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d:", twoD)
}