Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang: Global vars scope and routines

I’m trying to understand a problem I have using a global var and a routine.
I created a simplifed test case to demonstrate:

var _i int = 5

func main() {
    fmt.Println("a _i", _i)

    go func() {
        fmt.Println("b _i", _i)
        update()
    }()
    ...
}
    
func update() {
    fmt.Println("c _i", _i)
}

It correctly returns

a _i 5
b _i 5
c _i 5

But if I initialise my var inside main:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var _i int

func main() {
    _i := 5
    fmt.Println("a _i", _i)

    go func() {
        fmt.Println("b _i", _i)
        update()
    }()
    ...
}
    
func update() {
    fmt.Println("c _i", _i)
}

It returns

a _i 5
b _i 5
c _i 0

Anybody can explain what I’m missing here?
Thanks

>Solution :

In the last version you initialized _i with _i := 5 the := creates a new _i that shadows the global one. This is why update() prints 0, the global _i was never set to anything. You can change your initialization to _i = 5 to fix this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading