To import and use the flag
package in Go for command-line argument parsing, you can follow these steps:
flag
package in your code:import "flag"
name
and an integer argument named age
, you can define the variables as follows:var name string
var age int
flag
package to define the corresponding command-line flags and bind them to the variables. Use the StringVar
function for string flags and the IntVar
function for integer flags. For example:flag.StringVar(&name, "name", "", "Your name")
flag.IntVar(&age, "age", 0, "Your age")
Here, the first argument is the variable to bind the flag value to, the second argument is the flag name (including any shorthand notation), the third argument is the default value, and the fourth argument is a short description of the flag.
Parse
function of the flag
package:flag.Parse()
name
and age
to access the parsed command-line arguments.Here's a complete example that demonstrates how to import and use the flag
package:
package main
import (
"flag"
"fmt"
)
func main() {
// Define command-line flags
var name string
var age int
flag.StringVar(&name, "name", "", "Your name")
flag.IntVar(&age, "age", 0, "Your age")
// Parse command-line arguments
flag.Parse()
// Use the parsed values
fmt.Println("Name:", name)
fmt.Println("Age:", age)
}
In this example, you can run the program with command-line arguments like -name John -age 25
to set the corresponding variables.