In Go, you can use the flag
package to define and parse boolean command-line flags. Here's an example of how you can do this:
package main
import (
"flag"
"fmt"
)
func main() {
// Define a boolean flag using the flag.Bool function
// The first argument is the flag name, and the second argument is the default value
boolFlag := flag.Bool("flagname", false, "Description of the flag")
// Parse the command-line arguments to populate flag variables
flag.Parse()
// Access the value of the flag using the pointer
if *boolFlag {
fmt.Println("Flag is set to true")
} else {
fmt.Println("Flag is set to false")
}
}
In this example, the flag.Bool
function is used to define a boolean flag named flagname
with a default value of false
and a description. The flag.Parse()
function is called to parse the command-line arguments and populate the flag variable. The value of the flag can be accessed using the pointer *boolFlag
. If the flag is set to true
, it prints "Flag is set to true", otherwise it prints "Flag is set to false".
To use this program, you can run it from the command line with the flag -flagname=true
or -flagname=false
. If no flag is provided, it will use the default value of false
.