0

I'm actually new to go and I'm unable to find how to override scope of the variable in Go

consider this...

package main

import (
    "fmt"
)

var x = 10
var a int = 10

func main() {
    var a int = 20
    fmt.Println(a)
}

When I run it the output is 20 which means it actually prints the local scope variable

How can I display the global variable 'a' inside the main function

Nivas
  • 23
  • 6
  • 5
    *"How can I display the global variable 'a' inside the main function"*. By not creating a local variable with the same name. – mkopriva Jan 01 '19 at 17:25
  • 1
    1.) I didn't say it isn't possible in C/C++. 2.) Your question was about Go and so was my comment. – mkopriva Jan 02 '19 at 14:01

1 Answers1

4

What you're doing is called "variable shadowing". If you want to access the global variable, the only option is simply to not shadow it!

var a int = 10

func main() {
    var localA int = 20
    fmt.Println(a) // 10
    fmt.Println(localA) // 20
}

Of course, you could preserve the global value in a different local variable before shadowing. I can't imagine when this would actually be useful:

var a int = 10

func main() {
    globalA := a
    var a int = 20
    fmt.Println(a) // 20
    fmt.Println(globalA) // 10
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • I'm actually from C++ where we use it quite a few times while learning and it can be shadowed easily using ":" operator. So I was just thinking is it possible in Go. Thanks for your help. – Nivas Jan 01 '19 at 17:45
  • 2
    @Nivas That a language allows you to do something, doesn't mean it's a good idea! I've lost count of the number of bugs tracked down to a shadowed variable. At least in Go, `go vet -shadow` can help catch some of these before they cause serious problems. – Michael Hampton Jan 01 '19 at 19:41