Golang Working with Slices

Golang Working with Slices

Slices in golang are a special case of arrays. Slices are built on top of arrays. The difference between the slices and arrays are slices uses pointers when we use it (i.e when we pass it to a function or assign it to another variable) where as array passes the values. It makes arrays use more memory.

How to create slices in golang?

We can create slices using the make keyword. It takes three parameters.

  1. Type of array
  2. length
  3. capacity

Let's see an example

package main
import (
    "fmt"
)

func main(){
    var names = make([]string, 5, 6)
    fmt.Println(names)
    var numbers = make([]int, 3)
    fmt.Println(numbers)
    // without make
    myNumbers := []int{1,2,3}
    fmt.Println(myNumbers)
}

Output:

[    ]
[0 0 0]
[1 2 3]

Note: If didn't provide the capacity then it will consider it same as length.

Try the above code at play.golang.org

How make slices from existing arrays

We can make the slice without the make keyword and from an existing array. We use square brackets for this. Let's see an example.

package main
import (
    "fmt"
    "reflect"
)

func main(){
    names := [5]string{"John", "Henry", "Chanakya", "Ramanujan", "Shera"}
    start_index := 0
    end_index := 2
    names_slice = names[start_index:end_index]
    fmt.Println(reflect.TypeOf(names))
    fmt.Println(reflect.TypeOf(names_slice))
}

Output:

[5]string
[]string

See the slice underlying structure in the below image.

Golang Working with Slices

use of len and cap in go slices

  • We can make use of function len to calculate the length of a slice.
  • We can make use of function cap to calculate the capacity of a slice.

Let's see an example

package main
import (
    "fmt"
)

func main(){
    var names = make([]string, 5, 6)
    fmt.Println("length = ", len(names))
    fmt.Println("capacity = ", cap(names))
}

Output:

length =  5
capacity =  6

Increase capacity of a slice with "append" function golang

If we want to increase the capacity of a slice then we have to create the new slice with the more capacity and copy the data into it. To do it we don't need to write more code. We can achieve it with append built-in function.

Let's do some code

package main
import (
    "fmt"
)

func main(){
    // slice with capacity `1`
    slice := []int{45}
    // let's increase it's capacity with `append` function
    element1 := 10
    element2 := 20
    element3 := 30
    // we can use any number of arguments
    slice = append(slice, element1, element2, element3)
    fmt.Println("slice = ", slice)
}

Output:

slice =  [45 10 20 30]

References: