func main() { var myFlag bool flagSet := flag.NewFlagSet("myFlagSet", flag.ExitOnError) flagSet.BoolVar(&myFlag, "my-flag", false, "a boolean flag") err := flagSet.Parse(os.Args[1:]) if err != nil { log.Fatalf("failed to parse flags: %v", err) } // check if my-flag has been set ctx := flags.NewFlagContext(flagSet) if ctx.IsSet("my-flag") { fmt.Println("my-flag was set!") } else { fmt.Println("my-flag was not set.") } }
func main() { var myArg string flagSet := flag.NewFlagSet("myFlagSet", flag.ExitOnError) flagSet.StringVar(&myArg, "my-arg", "", "a positional argument") err := flagSet.Parse(os.Args[1:]) if err != nil { log.Fatalf("failed to parse flags: %v", err) } // check if my-arg has been set ctx := flags.NewFlagContext(flagSet) if ctx.ArgsLenAtDash() == 1 { fmt.Println("my-arg was set to:", ctx.Args()[0]) } else { fmt.Println("my-arg was not set.") } }In both examples, FlagContext is used to check if a flag or positional argument has been set by calling the IsSet method.