I have the following code
package main
import (
"fmt"
"flag"
)
var outputOnly bool
func something() string {
if outputOnly {
fmt.Println("outputting only")
} else {
fmt.Println("executing commands")
}
return "blah"
}
func main() {
vmoutputonlyPtr := flag.Bool("outputonly",false,"If set it will only output the commands it would execute, naturally without the correct parameter values set.")
flag.Parse()
outputOnly := *vmoutputonlyPtr
if outputOnly {
fmt.Println("outputonly commands will not execute")
}
var blah string
blah = something()
fmt.Println("blah is " + blah)
}
But the output is this:
$ ./se -outputonly
outputonly commands will not execute
executing commands
ie. it appears that the function something() is aware of the global variable, but does not reflect its true value. This is my first attempt at golang. What am I doing wrong?
The problem is this line in main
.
outputOnly := *vmoutputonlyPtr
:=
declares a new variable on the left, outputOnly
, of the type of the expression on the right, *vmoutputonlyPtr
and assigns the expression to it. It's equivalent to...
var outputOnly bool = *vmoutputonlyPtr
This new outputOnly
"shadows" your global outputOnly
in its scope. So all the code after outputOnly := *vmoutputonlyPtr
in main
refers to this outputOnly
local to main
. While something()
refers to the global outputOnly
.
See Redeclaration and Reassignment in Effective Go for more about variable shadowing in Go.
If you want to assign to an existing variable, just use =
.
outputOnly = *vmoutputonlyPtr