define slice golang code example
Example 1: 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))
}
Example 2: go slice
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
s = s[:0]
printSlice(s)
s = s[:4]
printSlice(s)
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}