In Go, you can use the flag
package to define and parse command-line flags. The flag
package provides various options to define alias flags and shorthand options for command-line flags.
Here's an example that demonstrates how to use flag aliases and shorthand options in Go:
package main
import (
"flag"
"fmt"
)
func main() {
// Define flags
name := flag.String("name", "", "Your name")
age := flag.Int("age", 0, "Your age")
verbose := flag.Bool("v", false, "Verbose output")
// Define flag aliases
flag.StringVar(name, "n", "", "Your name (alias)")
flag.IntVar(age, "a", 0, "Your age (alias)")
// Parse flags
flag.Parse()
// Access flag values
fmt.Println("Name:", *name)
fmt.Println("Age:", *age)
fmt.Println("Verbose:", *verbose)
}
In this example, we define three command-line flags: name
, age
, and verbose
. The name
flag uses an alias -n
, while the age
flag uses an alias -a
. The verbose
flag has an alias of -v
which is a shorthand option.
To run this program with command-line arguments:
$ go run main.go -n John -a 30 -v
The output will be:
Name: John
Age: 30
Verbose: true
Here, the -n
flag is used as an alias for name
, the -a
flag as an alias for age
, and the -v
flag as a shorthand option for verbose
.
Using flag aliases and shorthand options can provide more concise and convenient ways to specify command-line flags in your Go programs.