sajad torkamani

In a nutshell

A slice is a reference to a portion of an array. Changing the elements of a slice modifies the corresponding elements in the underlying array.

Define a slice

package main

import "fmt"

func main() {
	names := [4]string{"John", "Bob", "Jill", "Tim"}
	firstTwo := names[0:2]

	fmt.Println(names)

	firstTwo[0] = "Mike"
	fmt.Println(firstTwo)
}

Outputs:

[John Bob Jill Tim]
[Mike Bob]

Append to slice

package main

import "fmt"

func main() {
	var s []int
	printSlice(s)

	// append works on nil slices.
	s = append(s, 0)
	printSlice(s)

	// The slice grows as needed.
	s = append(s, 1)
	printSlice(s)

	// We can add more than one element at a time.
	s = append(s, 2, 3, 4)
	printSlice(s)
}

func printSlice(s []int) {
	fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

Iterate over slice

package main

import "fmt"

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
	for i, v := range pow {
		fmt.Printf("2**%d = %d\n", i, v)
	}
}
Tagged: Golang