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.

Recall, syntax of array type is: [n]type. The syntax for slice just omits the n.

Example:

[see Golang: Basic Datatypes]

package main

import "fmt"

func main() {

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

	// print the type
	fmt.Printf("%T", 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

package main

import "fmt"

func main() {

	var sl = []int{3, 4, 5}

	// print it normally
	fmt.Printf("%v\n", sl) // [3 4 5]

	// print in golang syntax
	fmt.Printf("%#v\n", sl) // []int{3, 4, 5}

}

Print Slice Line by Line

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

package main

import "fmt"

func printSlice(sliceInt []int) error {
	for k, v := range sliceInt {
		fmt.Printf("%v %v\n", k, v)
	}
	return nil
}

func main() {
	var sl = []int{3, 4, 5, 6}
	printSlice(sl)
}

// 0 3
// 1 4
// 2 5
// 3 6

[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.

example:

make([]int, 10, 1000) → create a slice of int, 10 slots, but with total of 1000 slots for growth.

Note: capacity is very useful for efficiency reasons, because, to grow, you have to use append(slice, …), and it returns a new slice, which is a costy operation.

package main

import "fmt"

func main() {

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

	// 3 slots 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 or set it to a subslice of 0 length.

mySlice = nil

or

mySlice = mySlice[0:0]

The recommended way is to set to nil.

Nested Slice

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

var x [][]int → declare

package main

import "fmt"

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

Nested Slice with Values

var y = [][]int{{3, 4}, {7}, {1, 2}} → declare 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

var ns = make([][]string, 2)

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. Example: for _, v := range slice {…}

The _ is called “blank identifier”.

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. Print String
  8. String Backslash Escape
  9. Rune
  10. Variable
  11. Zero Value
  12. Constant
  13. If Then Else
  14. Switch/Case
  15. Loop
  16. Basic Types
  17. Array
  18. Slice
  19. Map
  20. Struct
  21. Function
  22. Closure
  23. Pointer
  24. String, Byte Slice, Rune Slice
  25. regexp
  26. Read File
  27. Write to File
  28. Walk Dir
  29. Check File Exist
  30. System Call
  31. Get Script Path
  32. Defer
  33. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec