The flag package in Go provides a simple way to parse command-line arguments. If you're building a Go application that requires input from the user at the command line, the flag package is the way to go.
Importing the Flag Package
To get started, you need to import the flag package. Let's begin with a basic example:
package main
import (
"flag"
"fmt"
)
Defining Flags
You can define flags using various functions like flag.String, flag.Int, etc. Here is how you can define a string flag:
var name = flag.String("name", "World", "a name to say hello")
In this example, "name" is the flag's name, "World" is the default value, and "a name to say hello" is some helpful usage information.
Parsing Flags
After defining your flags, use flag.Parse() to parse the command-line arguments:
func main() {
flag.Parse()
fmt.Printf("Hello, %s!\n", *name)
}
Once parsed, the value can be retrieved using the pointer returned by the flag definition, in this case, *name.
Example Usage
Here's an example of how this application might be executed from the command line:
$ go run main.go --name=Alice
Hello, Alice!
If the flag is not specified, it defaults to the value "World", as provided in the flag definition:
$ go run main.go
Hello, World!
Defining Other Types of Flags
You can define other types of flags too:
Integer flag:
var age = flag.Int("age", 0, "user age")Boolean flag:
var debug = flag.Bool("debug", false, "enable debugging")
Custom Flag Value Types
For more complex data types, you can implement the flag.Value interface, which consists of Set and String methods.
type Celsius float64
func (c *Celsius) Set(s string) error {
// parse logic
return nil
}
func (c *Celsius) String() string {
return fmt.Sprintf("%v°C", *c)
}
func main() {
var temp Celsius
flag.Var(&temp, "temp", "the temperature")
flag.Parse()
fmt.Printf("Temperature: %v\n", temp)
}
This guide covers the basics of using the flag package to create and parse command-line flags in Go. With these tools, you can build robust and user-friendly command-line applications.