Showing posts with label go pass by reference. Show all posts
Showing posts with label go pass by reference. Show all posts

Friday, 3 May 2019

Go Language: Pass by Reference


HelloWorld.go
package main

import "fmt"

func main() {

 name := "Ram"

 changeMe(&name)

 fmt.Println("Hello!!!!! Mr.", name)

}

func changeMe(name *string){
 *name = "Krishna"
}

Output
Hello!!!!! Mr. Krishna


Previous                                                 Next                                                 Home

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