Thursday, 2 May 2019

Go Language: Arrays are passed by value


Unlike other languages, Array are passed by value in Go.

For example, if you call updateCountries method by passing an array as argument, the changes done for the array ‘countries’ inside the method ‘updateCountries’ is not reflected outside.

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

App.go
package main

import "fmt"

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

    countries[0] = "India"
    countries[1] = "Bangladesh"
    countries[2] = "Canada"
    countries[3] = "Austria"
    countries[4] = "Germany"

    fmt.Println(countries)

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

    updateCountries(countries)

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

func updateCountries(countries [5]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

[India Bangladesh Canada Austria Germany]



Previous                                                 Next                                                 Home

No comments:

Post a Comment