When building command-line applications in Go, efficiently parsing command-line arguments is crucial. The flag package is a part of Go's standard library that provides a simple way to parse command-line flags. In this article, we will explore how to use the flag package to handle command-line input.
Setting Up Flags
To get started with setting up flags, import the flag package and define variables that store the values of command-line arguments.
package main
import (
"flag"
"fmt"
)
func main() {
// Define a string flag with a default value of "world" and a short description.
name := flag.String("name", "world", "a name to say hello to")
// Define an integer flag with a default value of 0 and a short description.
age := flag.Int("age", 0, "your age")
// Parse the flag set from the command-line arguments.
flag.Parse()
fmt.Printf("Hello, %s! You are %d years old.\n", *name, *age)
}
Running the Code
To build the command-line tool, save the code in a file named main.go and run the following commands:
$ go build main.go
$ ./main --name=Alice --age=30
This should output:
Hello, Alice! You are 30 years old.
Understanding Flags
Flags can be specified in different ways. For example, long options can be written using two dashes like --name=Alice or with a space delimiter such as --name Alice. Short forms can be implemented separately if needed using external packages or custom logic.
Using Different Flag Types
The flag package also provides functions to define other types of flags:
var verbose = flag.Bool("verbose", false, "enable verbose mode")
// You can use other types similar to the following:
var pi = flag.Float64("pi", 3.14, "value of pi")
var help = flag.Bool("help", false, "show help")
Default Values and Help
If you run the program without any arguments, you'll see the output using the default values:
$ ./main
Hello, world! You are 0 years old.
To automatically show usage documentation generated by the flag package, you can use:
flag.Usage()
This prints all the flags available along with their descriptions.
Conclusion
Utilizing the flag package in Go not only simplifies handling command-line arguments but also provides built-in help text generation and type consistency across flags.