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