Reputation: 7584
I'm messing with the flag library, and found that this code does not work:
package main
import (
"fmt"
"flag"
)
var recursive bool
func init() {
recursive = *flag.Bool("r", false, "Search recursively")
}
func main() {
flag.Parse()
fmt.Printf("Recursive: %t \n\n", recursive)
flag.PrintDefaults()
}
But this does (I commented the three lines I changed):
package main
import (
"fmt"
"flag"
)
var recursive *bool //Changed to pointer type
func init() {
recursive = flag.Bool("r", false, "Search recursively") //Changed to not dereference function
}
func main() {
flag.Parse()
fmt.Printf("Recursive: %t \n\n", *recursive) //Changed to dereference variable
flag.PrintDefaults()
}
Why does this behave like this? Are functions not allowed to be dereferenced in Golang, or am I doing something else wrong?
Upvotes: 1
Views: 1228
Reputation: 418635
The reason for this is because when you call flag.Bool()
, it does not yet parse the command line arguments, it just defines a named flag and initializes it with the default value (which is false
as you specified it).
Command line arguments are only parsed when you call flag.Parse()
. If you use recursive bool
, in the init()
function the default false
will be assigned to it. The flag
package does not know about your recursive
variable, so later when you call flag.Parse()
, its value will not/ cannot be changed.
flag.Bool()
returns a pointer to a bool
variable which the flag
package knows about, and later when you call flag.Parse()
the pointed bool
variable will be properly updated, so when you print the pointed valued after flag.Bool()
, it will be the updated value which will be set based on your command line arguments.
So you must store and use the pointer returned by flag.Bool()
else you will only see the default value. Or you can let the flag
package know about your recursive
variable: you can tell the flag
package that you what it to store the result into your recursive
variable by telling this with the flag.BoolVar()
function:
flag.BoolVar(&recursive, "r", false, "Search recursively")
Note that in this case there is no return value, becase you explicitly provided a pointer to a bool
which you want the flag
package to store the result to.
Upvotes: 2