/* * A short example of doing things with subranges of slices * @authord ggtowell * Created: July 25, 2021 */ package main import "fmt" func main() { // create a slice containing integers and populate it with 1..10 s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} fmt.Printf("s=%v\n", s) // a couple of the item in the slice v := s[2:4] fmt.Printf("v=%v\n", v) // fill w with two separate pieces of slice var w []int fmt.Printf("w=%v\n", w) for _, val := range s[1:3] { w = append(w, val) } // it is a lot easier to use varidic append than writing a loop ... on the other hand I never remember this syntax. w = append(w, s[6:8]...) fmt.Printf("w=%v\n", w) // another way to copy pieces -- note that this way overwrites // start by making a slice of length 6 z := make([]int, 6) /** Equivalent to the make var z []int for i:=0; i<6; i++ { z = append(z, 0) } **/ fmt.Printf("z=%v\n", z) //then use copy function to get the parts into new slice // note that this appproach leaves "holes" copy(z[0:1], s[2:4]) copy(z[3:5], s[6:8]) fmt.Printf("z=%v\n", z) ss() } // the pointer issue does not really arise unless you are using structs. func ss() { ss := make([]string, 1) aa := "asdf" ss = append(ss, aa) fmt.Println(aa) fmt.Println(ss) aa = aa[0:2] fmt.Println(aa) fmt.Println(ss) }