Golang : Pass by Value Vs Pass by Refere

By default every thing in go is pass by value, which means if you pass any argument to a function, it would copy the values passed in another variable and make changes to it in function scope only (with in function block) and does not modify the original value.

Which means whatever you pass to a function in Golang remains immutable and does not get modified. However, if you use pointer then changes would impact the original value.

Try to read below program and understand it:

package main

import "fmt"

type Person struct {
       firstName string
       lastName  string
}

func changeName(p Person) {
       p.firstName = "Bad"
       fmt.Print("inside method with local scope on copy")
       fmt.Println(p)
}

func changeNameWithPointer(p *Person) {
       p.firstName = "Bad"
       fmt.Print("inside method with local scope on pointer")
       fmt.Println(p)
}

func main() {
       person := Person{
              firstName: "Good",
              lastName:  "person",
       }
       fmt.Println("Original value of person", person)
       changeName(person)
       fmt.Print("Outside method with original variable passed as copy")
       fmt.Println(person)

       fmt.Println("\n\n========Pass by pointer will modify values =======")

       fmt.Println("Outside method with original variable", person)
       changeNameWithPointer(&person)
       fmt.Println("Outside method with original variable passed as reference (which is now changed )")
       fmt.Println(person)
}

 

Sample output :

➜ passByValue git:(master) ✗ go run ValueVsReference.go
Original value of person {Good person}
inside method with local scope on copy{Bad person}
Outside method with original variable passed as copy{Good person}
========Pass by pointer will modify values =======
Outside method with original variable {Good person}
inside method with local scope on pointer&{Bad person}
Outside method with original variable passed as reference (which is now changed )
{Bad person}

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s