Golang flag.FlagSet.Parse() and Parsed() functions example

package flag

Parse parses flag definitions from the argument list, which should not include the command name. Must be called after all flags in the FlagSet are defined and before flags are accessed by the program. The return value will be ErrHelp if -help was set but not defined.

Golang flag.FlagSet.Parse() function usage example

 package main

 import (
 "flag"
 "fmt"
 )


 var (
 flagSet *flag.FlagSet
 )


 func init() {
 flagSet = flag.NewFlagSet("example", flag.ContinueOnError)

 }

 func main() {

 flagSet.String("file", "", "filename to view")

 flagSet.Int("timeout", 5000, "specify the time in milliseconds to wait for a response")


 err := flagSet.Parse([]string{"file","timeout"})

 if err != nil {
 fmt.Println(err)
 }

 fmt.Println("Parsed the flag ? :", flagSet.Parsed())
 }

Output :

Parsed the flag ? : true

References :

http://golang.org/pkg/flag/#FlagSet.Parse

http://golang.org/pkg/flag/#FlagSet.Parsed

Advertisement