Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-slicing slices in Golang

Tags:

I recently picked up the Go language, and now I am confused with the following code:

package main  import "fmt"  func main() {     a := make([]int, 5)     printSlice("a", a)     b := make([]int, 0, 5)     printSlice("b", b)     c := b[:2]     printSlice("c", c)     d := c[2:5]     printSlice("d", d) }  func printSlice(s string, x []int) {     fmt.Printf("%s len=%d cap=%d %v\n",         s, len(x), cap(x), x) } 

And the result:

a len=5 cap=5 [0 0 0 0 0] b len=0 cap=5 [] c len=2 cap=5 [0 0] //why the capacity of c not 2 but 5 instead d len=3 cap=3 [0 0 0] 
like image 396
Coder Avatar asked Oct 07 '12 12:10

Coder


People also ask

How do I return a slice in Golang?

In Go, there are two functions that can be used to return the length and capacity of a slice: len() function - returns the length of the slice (the number of elements in the slice) cap() function - returns the capacity of the slice (the number of elements the slice can grow or shrink to)

How do I slice an array in Golang?

Create slice from an array in Golang Now, we can slice the specified elements from this array to create a new slice. Here, 4 is the start index from where we are slicing the array element. 7 is the end index up to which we want to get array elements.


1 Answers

c is a slice taken from the array b. This isn't a copy, but just a window over the 2 first elements of b.

As b has a capacity of 5, c could be extended to take the 3 other places (in fact it makes a new slice but over the same place in memory).

The maximal capacity of the slice is the capacity of the underlying array minus the position of the start of the slice in the array :

 array : [0 0 0 0 0 0 0 0 0 0 0 0]  array :  <----   capacity   --->  slice :     [0 0 0 0]  slice :      <---- capacity --->  

Maybe this program will make it more clear that c and d are just windows over b :

func main() {     b := make([]int, 0, 5)     c := b[:2]     d := c[1:5] // this is equivalent to d := b[1:5]     d[0] = 1     printSlice("c", c)     printSlice("d", d) } 

Output :

c len=2 cap=5 [0 1] // modifying d has modified c d len=4 cap=4 [1 0 0 0]  
like image 80
Denys Séguret Avatar answered Sep 19 '22 12:09

Denys Séguret