Showing posts with label go slices. Show all posts
Showing posts with label go slices. Show all posts

Thursday, 2 May 2019

Go language: Slices are passed by reference


In Go language, Arrays are passed by value, whereas slices are passed by reference.

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

For example, if you call updateCountries method by passing a slice as an argument, the changes done for the slice ‘countries’ inside the method ‘updateCountries’ will be reflected outside.

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]





Previous                                                 Next                                                 Home

Go Language: Arrays vs slices


a.   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.
b.   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.
c.    Arrays are passed by value, whereas slices are passed by reference.




Previous                                                 Next                                                 Home