goreference

Why doesn't variable increment?


I have a simple module in Go. Why is a variable not getting incremented when calling Some function?

package example

import "strconv"

var a int = 0

func Some() string {
    incr(a)
    return "example" + strconv.Itoa(a)
}

func incr(a int) {
    a++
}

Solution

  • Because you are passing the value of a. The local a inside incr has incremented.
    But not the you have globally created using var a int = 0

    If you want you can pass in by reference. Read the difference here

    In the below example, i have created two versions of the same method. One does pass by value other pass by reference. Look at the difference in value between a and b.

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    var a int = 0
    var b int = 0
    
    func Some() string {
        incr(a)
        return "example" + strconv.Itoa(a)
    }
    
    func Some2() string {
        incrPassByReference(&b)
        return "example" + strconv.Itoa(b)
    }
    
    func incr(a int) {
        a++
        fmt.Println("passed by value a", a)
    }
    
    func incrPassByReference(b *int) {
        *b++
        fmt.Println("passed by value b", *b)
    }
    
    func main() {
        val := Some()
        val2 := Some2()
        fmt.Println("original a", val)
        fmt.Println("original b", val2)
    }
    

    Playground