Slices in Go

Go: Slices

Slices are an important data type in Go, it provides a convenient and efficient way of working with sequences of typed data than arrays. Slices are analogous to arrays, but have some unusual properties. In this article we will look at what slices are and how they are used in Golang.

1. Slice declaration and initialization in Go

  • Using array literal
    letters := []string{"a", "b", "c", "d"}
  • Using make function
    // syntax
    func make([]T, len, cap) []T

    // example
    var s []byte
    s = make([]byte, 5, 5)
    // s == []byte{0, 0, 0, 0, 0}
  • Slices modification
    // you can modify values like this
    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    // push values like we do in array
    s = append(s, "d")
    s = append(s, "e", "f")
    fmt.Println("apd:", s)

2. Copy Slices in Go

Slices can also be copy’d. Here we create an empty slice c of the same length as s and copy into c from s.

    c := make([]string, len(s))
    copy(c, s)
    fmt.Println("cpy:", c)

3. slice operator

Slices support a “slice” operator with the syntax slice[low:high], which will return new Slices with elements from indexes low to high-1

    var s []byte    
    s = make([]byte, 5, 5)
    l = s[:5]
    fmt.Println("sl2:", l)

4. Slices as multi-dimensional data structure

Slices can be composed into multi-dimensional data structures. The length of the inner slices can vary, unlike with multi-dimensional array

    twoDSlice := make([][]int, 3)
    for i := 0; i < 3; i++ {
        innerLen := i + 1
        twoDSlice[i] = make([]int, innerLen)
        for j := 0; j < innerLen; j++ {
            twoDSlice[i][j] = i + j
        }
    }
    fmt.Println("2d: ", twoDSlice)
    //2d:  [[0] [1 2] [2 3 4]]

Previous Article

Next Article