package main import ( "flag" "fmt" ) func main() { fs := flag.NewFlagSet("myprog", flag.ExitOnError) var name string fs.StringVar(&name, "name", "", "the name of the person") err := fs.Parse([]string{"--name", "John"}) if err != nil { fmt.Println(err) return } fmt.Println("Hello, " + name) }
Hello, John
package main import ( "flag" "fmt" ) func main() { fs := flag.NewFlagSet("myprog", flag.ExitOnError) var name string fs.StringVar(&name, "name", "", "the name of the person") fs.Parse([]string{"--name", "John"}) args := fs.Args() fmt.Println("Hello, " + name) fmt.Println("Additional args:", args) }
Hello, John Additional args: []In the first example, we parse only one argument after the flag. In the second example, we use Arg to parse any additional arguments after the flags have been parsed. Overall, the flag package provides an easy-to-use, lightweight solution for parsing command-line arguments in Go.