"os" ) ! func main() { help := flag.Bool("help", false, "print help message and exit") flag.Parse() ! if *help { fmt.Println("demo.go - This is a demo of flag pkg.") os.Exit(0) } ! fmt.Println("Hello, Gopher!") }
"Gopher", "set your name") flag.Parse() ! ...snip... ! fmt.Printf("Hello, %v!\n", *name) } $ go run demo.go Hello, Gopher! ! $ go run demo.go --name zoncoen Hello, zoncoen! ! $ go run demo.go --name=zoncoen Hello, zoncoen!
flag.Bool("help", false, "print help message and exit") flag.BoolVar(help, "h", false, "print help message and exit") flag.Parse() ! ...snip... $ go run demo.go --help demo.go - This is a demo of flag pkg. ! $ go run demo.go -h demo.go - This is a demo of flag pkg.
if *help { fmt.Println("demo.go - This is a demo of flag pkg.") flag.Usage() os.Exit(0) } ! ...snip... $ go run demo.go -h demo.go - This is a demo of flag pkg. Usage of /var/folders/c3/vwntnjg517v2pxzd6072hrnjhggkq_/T/go- build178147611/command-line-arguments/_obj/exe/demo: -h=false: print help message and exit -help=false: print help message and exit -name="Gopher": set your name
name string parsed bool actual map[string]*Flag formal map[string]*Flag args []string errorHandling ErrorHandling output io.Writer } // flag.go L278-283 type Flag struct { Name string Usage string Value Value DefValue string } • formal ొ͞Εͨϑϥά໊σϑΥϧτΛ อ࣋