Skip to content

Instantly share code, notes, and snippets.

@mmirolim
Created August 11, 2015 18:25
Show Gist options
  • Select an option

  • Save mmirolim/4f8008a342a89d35a0b9 to your computer and use it in GitHub Desktop.

Select an option

Save mmirolim/4f8008a342a89d35a0b9 to your computer and use it in GitHub Desktop.
package main
// Example explaining how slices works
// About slice's capacity, pointers and copies
import "fmt"
func main() {
// let's create slice with len 2 and capacity 3
sl := make([]int, 2, 3)
fmt.Println("slice sl cap=", cap(sl))
// if you need pointer to slice data make it explicit
psl := &sl
// set value to first slice element
sl[0] = 11
fmt.Println("slice sl and pointer to it psl", sl, psl)
// this is how you can change original slice through pointer
(*psl)[0] = 21
fmt.Println("original slice element sl[0] changed through pointer (*psl)[0]", sl)
// add more data then capacity of original slice
// new memory block will be allocated to hold new values
// capacity will double
sl = append(sl, []int{2, 3, 4}...)
fmt.Println("sl cap increased after append cap =", cap(sl))
// if you need copy slice make it explicitly
// first prepare slice where to copy
csl := make([]int, len(sl))
// now copy from original slice to new slice which will hold data
copy(csl, sl)
// try to change slice copy, it will not change original slice
csl[0] = 77
fmt.Println("slice sl, pointer to slice psl and copy of slice csl", sl, psl, csl)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment