To support long and short flag names in Go, you can make use of the flag
package. Here's an example of how you can achieve this:
package main
import (
"flag"
"fmt"
)
func main() {
verbose := flag.Bool("verbose", false, "Enable verbose mode")
shortVerbose := flag.Bool("v", false, "Short verbose mode")
flag.Parse()
if *verbose || *shortVerbose {
fmt.Println("Verbose mode enabled")
} else {
fmt.Println("Verbose mode disabled")
}
// Rest of your application logic...
}
In this example, we define two flags: verbose
and v
. The flag.Bool
function is used to declare boolean flags. The first argument is the name of the flag, followed by its default value, and a description.
After defining the flags, we call flag.Parse()
to parse the command-line arguments and set the values of the flags accordingly.
By default, long flag names are prefixed with --
(e.g., --verbose
), while short flag names are prefixed with a single -
(e.g., -v
). Both flag names will work interchangeably, and the corresponding flag value will be set to true
if the flag is provided in the command-line arguments.
You can access the flag values using the *
operator on the flag variables, as shown in the example.
Note that to use the flag
package, you need to import it:
import "flag"
This is a simple way to support both long and short flag names in Go using the flag
package.