import ( "fmt" "github.com/spf13/pflag" ) func main() { // Define flags var username string var age int var verbose bool flagSet := pflag.NewFlagSet("myapp", pflag.ExitOnError) flagSet.StringVar(&username, "username", "", "The user's name") flagSet.IntVar(&age, "age", 0, "The user's age") flagSet.BoolVar(&verbose, "verbose", false, "Enable verbose output") // Parse command-line arguments flagSet.Parse() // Print values of flags fmt.Printf("Username: %s\n", username) fmt.Printf("Age: %d\n", age) fmt.Printf("Verbose: %t\n", verbose) // Iterate over all flags flagSet.VisitAll(func(flag *pflag.Flag) { fmt.Printf("Flag: %s, Value: %v\n", flag.Name, flag.Value) }) }
import ( "github.com/spf13/pflag" ) func main() { // Define flags var configPath string flagSet := pflag.NewFlagSet("myapp", pflag.ExitOnError) flagSet.StringVar(&configPath, "config", "", "Path to config file") // Parse command-line arguments flagSet.Parse() // Load config file if configPath != "" { // ... } }In this example, we define a flag `config` using the FlagSet object. We then parse the command-line arguments using the `Parse` method and check if the `configPath` flag is set. If it is, we can load the config file based on its path.