Golang: Slice of Slice

By Xah Lee. Date: .

Slice of Slice

s[a:b]
  • Return a slice of s from index a to b.
  • The a is included, The b is excluded.
  • The result shares the same data with original. If you modify it, the original is also modified.
s[:n]

Same as s[0:n]

s[n:]

Same as s[n:len(s)]

Example: Slice of Slice

package main

import "fmt"

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

	// take a slice of values
	var x = s[1:3]

	fmt.Println(x) // [1 2]
}

Example: Slice of Slice Shares Data

Here's a example where modifying the slice also modifies the original.

package main

import "fmt"

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

	// take a slice
	var x = s[1:3]

	// modify it
	x[0] = 99

	// original also changed
	fmt.Printf("%v\n", s)
	// [0 99 2 3]

}

Golang, array and slice