In Go, the flag
package provides a convenient way to parse command-line arguments. You can define various types of flags using the FlagType()
functions available in the package. Here is an example of using different flag types:
FlagType()
function. For example:// Define a string flag
name := flag.String("name", "John Doe", "Specify your name")
// Define an integer flag
age := flag.Int("age", 0, "Specify your age")
// Define a boolean flag
isStudent := flag.Bool("student", false, "Specify if you are a student")
flag.Parse()
to parse the command-line arguments. This will populate the flag variables with values provided as arguments.flag.Parse()
fmt.Println("Name:", *name)
fmt.Println("Age:", *age)
fmt.Println("Is Student:", *isStudent)
go run main.go -name "Alice" -age 25 -student
Output:
Name: Alice
Age: 25
Is Student: true
Note that for boolean flags, passing the flag without a value sets it to true
, while omitting the flag sets it to false
.
Additionally, you can customize flag parsing behavior using other functions provided by the flag
package, such as flag.StringVar()
, flag.Parse()
or flag.Usage()
.