1

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?

1
  • Ah you're right, thanks!! Should I edit it, or would that be considered bad form since it would make your comment and the top answer appear wrong? Commented Jan 13, 2015 at 8:33

1 Answer 1

2

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.

Alternative: Register your variable

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.