what is a slice in golang code example

Example 1: create slice golang

b := [2]string{"Penn", "Teller"}

Example 2: go slice

// loop over an array/a slice
for i, e := range a {
    // i is the index, e the element
}

// if you only need e:
for _, e := range a {
    // e is the element
}

// ...and if you only need the index
for i := range a {
}

// In Go pre-1.4, you'll get a compiler error if you're not using i and e.
// Go 1.4 introduced a variable-free form, so that you can do this
for range time.Tick(time.Second) {
    // do it once a sec
}

Example 3: golang slice

package main

import (
	"fmt"
)

func main() {
	var slice = []int{1, 2, 3, 4, 5}
	var store = make([]int, 3)

	push := append(slice, 6, 7, 8, 9)
	copy(store, slice)

	fmt.Println("before append value", slice)
	fmt.Println("after append value", push)
	fmt.Println("render value all value exist", push[:])
	fmt.Println("render value after second value", push[2:])
	fmt.Println("render value before third index", push[:3])
	fmt.Println("render value start from zero and last value before second index", push[0:2])
	fmt.Println("merge slice value", store)
	fmt.Println("read size slice", len(slice))
	fmt.Println("read capacity slice", cap(slice))
}

Tags:

Go Example