1
+ // Code listing 11: https://play.golang.org/p/Z3_U32sn8RF
2
+
3
+ // _Slices_ are a key data type in Go, giving a more
4
+ // powerful interface to sequences than arrays.
5
+
6
+ package main
7
+
8
+ import "fmt"
9
+
10
+ func main () {
11
+
12
+ // Unlike arrays, slices are typed only by the
13
+ // elements they contain (not the number of elements).
14
+ // To create an empty slice with non-zero length, use
15
+ // the builtin `make`. Here we make a slice of
16
+ // `string`s of length `3` (initially zero-valued).
17
+ s := make ([]string , 3 )
18
+ fmt .Println ("emp:" , s )
19
+
20
+ // We can set and get just like with arrays.
21
+ s [0 ] = "a"
22
+ s [1 ] = "b"
23
+ s [2 ] = "c"
24
+ fmt .Println ("set:" , s )
25
+ fmt .Println ("get:" , s [2 ])
26
+
27
+ // `len` returns the length of the slice as expected.
28
+ fmt .Println ("len:" , len (s ))
29
+
30
+ // In addition to these basic operations, slices
31
+ // support several more that make them richer than
32
+ // arrays. One is the builtin `append`, which
33
+ // returns a slice containing one or more new values.
34
+ // Note that we need to accept a return value from
35
+ // `append` as we may get a new slice value.
36
+ s = append (s , "d" )
37
+ s = append (s , "e" , "f" )
38
+ fmt .Println ("apd:" , s )
39
+
40
+ // Slices can also be `copy`'d. Here we create an
41
+ // empty slice `c` of the same length as `s` and copy
42
+ // into `c` from `s`.
43
+ c := make ([]string , len (s ))
44
+ copy (c , s )
45
+ fmt .Println ("cpy:" , c )
46
+
47
+ // Slices support a "slice" operator with the syntax
48
+ // `slice[low:high]`. For example, this gets a slice
49
+ // of the elements `s[2]`, `s[3]`, and `s[4]`.
50
+ l := s [2 :5 ]
51
+ fmt .Println ("sl1:" , l )
52
+
53
+ // This slices up to (but excluding) `s[5]`.
54
+ l = s [:5 ]
55
+ fmt .Println ("sl2:" , l )
56
+
57
+ // And this slices up from (and including) `s[2]`.
58
+ l = s [2 :]
59
+ fmt .Println ("sl3:" , l )
60
+
61
+ // We can declare and initialize a variable for slice
62
+ // in a single line as well.
63
+ t := []string {"g" , "h" , "i" }
64
+ fmt .Println ("dcl:" , t )
65
+
66
+ // Slices can be composed into multi-dimensional data
67
+ // structures. The length of the inner slices can
68
+ // vary, unlike with multi-dimensional arrays.
69
+ twoD := make ([][]int , 3 )
70
+ for i := 0 ; i < 3 ; i ++ {
71
+ innerLen := i + 1
72
+ twoD [i ] = make ([]int , innerLen )
73
+ for j := 0 ; j < innerLen ; j ++ {
74
+ twoD [i ][j ] = i + j
75
+ }
76
+ }
77
+ fmt .Println ("2d: " , twoD )
78
+ }
0 commit comments