Golang: Slice

By Xah Lee. Date: . Last updated: .

Slice is like array but length can be changed.

Syntax of Slice Type

[]type → syntax for the type of slice with each slot of type type.

Example:

Recall, syntax of array type is :

[n]type

The syntax for slice just omits the n.

[see Golang: Basic Datatypes]

package main

import "fmt"

func main() {

    // declare var of type slice
    var ss []int

    // print the type
    fmt.Printf("%T\n", ss) // []int
}

Literal Expression of Slice

[]type{v1, v2 …} → create a slice with values.

package main

import "fmt"

func main() {

    // slice
    var ss = []int{9, 2, 6}

    fmt.Printf("%v\n", ss) // [9 2 6]
    fmt.Printf("%T\n", ss) // []int

}

Print Slice

To print each member on a line, you have to do a loop.

[see Golang: loop]

Create slice with 「make」

You can create a slice with make. It lets you specify how many items to begin with, and capacity for growth.

Note: capacity is not necessary. Go slice will automatically grow when needed. But specifying capacity can make your program microsecends faster.

package main

import "fmt"

func main() {

    // 3 items of int
    var s = make([]int, 3)
    fmt.Println(s) // [0 0 0]

    // 3 items of int, capacity of 9
    var s2 = make([]int, 3, 9)
    fmt.Println(s2) // [0 0 0]

}

length of slice

len(s) → returns the length of slice s.

Take a slice of slice

s[a:b] → returns a slice of s from index a to b. The a is included, The b is excluded.

package main

import "fmt"

func main() {
    var s = []int{0, 1, 2, 3}

    // take a slice of values
    fmt.Println(s[1:3]) // [1 2]
}

Append to Slice

use builtin function append.

var s2 = append(s1, 8, 9)

it returns a new slice.

package main

import "fmt"

func main() {

    var ss = []int{3, 5}

    var s2 = append(ss, 8, 9)

    fmt.Println(s2) // [3 5 8 9]

    // original not changed
    fmt.Println(ss) // [3 5]

}

Clear Slice

To clear slice, set it to nil.

mySlice = nil

Note: it also make the capacity to 0, but it's the recommended way.

Nested Slice

Slices can be nested. Just declare that the slots are also type slice.

var y = [][]int{{3, 4}, {7, 8, 9}, {1, 2}}

package main

import "fmt"

func main() {
    // x is slice of slice of int
    var x [][]int
    fmt.Println(x) // []
}

Nested slice with values.

package main

import "fmt"

func main() {

    // y is slice of slice of int
    var y = [][]int{{3, 4}, {7, 8, 9}, {1, 2}}

    fmt.Println(y) // [[3 4] [7 8 9] [1 2]]
}

Create nested slice with make.

package main

import "fmt"

func main() {

    // nested slice. 2 items. each item is a slice of string
    var ns = make([][]string, 2)

    // fill the slots
    ns[0] = []string{"a", "b"}
    ns[1] = []string{"x", "y", "z"}

    fmt.Println(ns) // [[a b] [x y z]]
}

Getting and setting values.

package main

import "fmt"

func main() {

    var ss = make([][]int, 2)

    ss[0] = []int{1, 2}
    ss[1] = []int{3, 4}

    ss[1][1] = 5

    fmt.Println(ss) // [[1 2] [3 5]]
}

Loop Thru Slice

for i, v := range slice {…} → loop thru slice, where i is current index and v the value.

if a variable is not used, name it _ to stop compiler from complaining. for _, v := range s

package main

import "fmt"

func main() {
    var s = []int{9, 2, 8, 61}
    for i, x := range s {
    fmt.Println(i, x)
    }
}

// 0 9
// 1 2
// 2 8
// 3 61

Reference

The Go Programming Language Specification - The Go Programming Language#Slice_types

The Go Programming Language Specification - The Go Programming Language#Appending_and_copying_slices

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Source Encoding
  3. Package, Import
  4. Comment
  5. Print
  6. String
  7. Rune
  8. String as Chars
  9. Variable
  10. Zero Value
  11. Constant
  12. If Then Else
  13. Switch/Case
  14. Loop
  15. Basic Types
  16. Array
  17. Slice
  18. Map
  19. Struct
  20. Function
  21. regexp
  22. Read File
  23. Write to File
  24. Walk Dir
  25. Check File Exist
  26. System Call
  27. Get Script Path
  28. Pointer
  29. Defer
  30. Random Number

Examples

  1. match any regexp
  2. Validate Links
  3. Generate Sitemap

Reference

  1. Go Spec