Go has a different way compared to languages such as Java, Scala and C in handling commandline arguments and flags. There are built in utility to generate commandline help message and assign default values to flags. One can create flags that maps to more complex data types.

Commandline Arguments

The main function which acts as the entry point of the program doesn’t take arguments. To read arguments from command line you will find them in os.Args

import "os"

func main() {
	for i:=0; i< len(os.Args); i++ {
		println(os.Args[i])
	}
}

Flags

f := flag.String("f","default value of this flag", "some interesting flag")
flag.Parse()
println(*f)
arguments :=

flag package gives a convenient function to reach commandline arguments without the flags using flag.Args(). Of course, you can declare as many flags as you want. You can also use other types such a boolean flag using flag.Bool(...) function. One thing to note, the call to flag.Parse() must proceed calling flag.Args()

Custom Flags

To create a custom flag we need to satisfy the flag.Value interface. I am using a simple example custom parsing a float. Note that we are reinventing flag.Float64() for demonstration purposes.

type floatFlag struct {
	 float64
}

func (m *floatFlag) String() string {
	return fmt.Sprintf("%v", m.float64)
}

func (m *floatFlag) Set(s string) error {
	m.float64, _ = strconv.ParseFloat(s, 32)
	return nil
}

We defined a new type floatFlag that satisfies the flag.Value interface. Thus it has the String and Set methods. This is a simple implementation without error handling. Now we need the following in our main to use this custom flag.

f:= floatFlag{9} // set default value
	flag.CommandLine.Var(&f, "flag-name", "usage of this test flag")
	flag.Parse()
	fmt.Println(f.float64) // will give us the value passed to commandline 

Now if we call our app with -flag-name 2.5, the value of f.float64 will be 2.5


Resources

  1. Ultimate Go Programming
  2. The Go Programming Language
  3. Go Documentation
  4. A tour of Go
  5. Go wiki: Switch
  6. The Go Programming Language Specification
  7. Go by Example