Thursday 2 May 2019

Go language: Slices


Arrays are fixed in size. If you create an array of size 6, then it can able to store exactly 6 elements. You can’t store more than 6 elements in the array, but slices can be resized on demand.

Slices are built on top of arrays. If you are changing any value of the slice, then it is going to change the value of underlying array and vice versa.

How to create a slice?
You can create a slice using built-in make function or indexing notation. ‘make’ function takes three arguments type, length and capacity.

Syntax
make([]Type, length, capacity)
make([]Type, length)
[]Type{}
[]Type{value1, value2, ..., valueN}

type: Specified the type of elements in the slice
length: tells you how many items are in the array.
capacity: Tells you the capacity of the underlying array. This the length of the hidden array.

App.go
package main

import "fmt"

func main() {
    data := make([]int, 5, 20)

    fmt.Println("Length : ", len(data))
    fmt.Println("Capacity : ", cap(data))
    fmt.Println("Data : ", data)
}


Output
Length :  5
Capacity :  20
[0 0 0 0 0]

Slices are passed by reference in Go.


App.go
package main

import "fmt"

func main() {
    countries := []string{}

    countries = append(countries, "India")
    countries = append(countries, "Bangladesh")
    countries = append(countries, "Canada")
    countries = append(countries, "Austria")
    countries = append(countries, "Germany")

    fmt.Println(countries)

    fmt.Println("\nUpdating countries with Dummy data")

    updateCountries(countries)

    fmt.Println()
    fmt.Println(countries)
}

func updateCountries(countries []string) {
    countries[0] = "Dummy"
    countries[1] = "Dummy"
    countries[2] = "Dummy"
    countries[3] = "Dummy"
    countries[4] = "Dummy"
}


Output
[India Bangladesh Canada Austria Germany]

Updating countries with Dummy data

[Dummy Dummy Dummy Dummy Dummy]

Note

a.   Arrays are passed by value in Go, whereas slices are passed by reference



Previous                                                 Next                                                 Home

1 comment: