SPONSORED ADS

Golang passing by reference and value

Last Updated Feb 28, 2023

Everything is pass by value in golang. See this example:

var foo = "beep boop"

If you pass foo by value, it means passing "beep boop". If you modified it, it will not affect foo.

package main

import "fmt"

// working at the flower shop will increase my kindness
func workingAtTheFlowerShop(stat string) {
    stat = "Angelic"
}

func main() {
    myKindness := "Inoffensive"

    workingAtTheFlowerShop(myKindness)
    fmt.Println(myKindness)
}

The workingAtTheFlowerShop func takes stat and change it.

But still, the output is Inoffensive, not Angelic. This is because the workingAtTheFlowerShop function receives a copy of myKindness, and any modified are not reflected at all.

If we want to modify the original value of myKindness, we need to pass a pointer to myKindness instead of the value of myKindness.

This is known as passing by reference.

passing by reference

package main

import "fmt"

func workingAtTheFlowerShop(stat *string) {
    *stat = "Angelic"
}

func main() {
    myKindness := "Inoffensive"
    workingAtTheFlowerShop(&myKindness)
    fmt.Println(myKindness)
}

In this version of the code, we pass a pointer to myKindness to the workingAtTheFlowerShop func using the & operator. Within the workingAtTheFlowerShop function, we dereference the pointer using the * operator to access the value of myKindness and modified it.

The output of this program is Angelic.

Golang pass by value

The variable is fully evaluated and the result value is copied into the func. Func can modified it but that mean nothing to the variable itself.

Golang pass by reference

The pointer to that variable (think of it as address to your home) is copied into the func. The func then dereferencing that pointer to find the real variable and modified it.

What is it use for or why I should understand this shit ?

  1. If we allow a func to modified the variable we pass to it. Then use a pointer.
  2. Another reason pointers are passed is to reduce the size of the value being passed. For example a large struct with a lot of data.

That's it. I hope this tutorial helped clear up any questions you had about the golang pointer.

See ya next time!

Hi there. Nodeepshit is a hobby website built to provide free information. There are no chargers to use the website.

If you enjoy our tutorials and examples, please consider supporting us with a cup of beer, we'll use the funds to create additional excellent tutorials.

If you don't want or unable to make a small donation please don't worry - carry on reading and enjoying the website as we explore more tutorials. Have a wonderful day!