Golang flag.FlagSet.NFlag() and Set() function example

package flag

NFlag returns the number of flags that have been set.

Set sets the value of the named flag.

Golang flag.FlagSet.NFlag() and Set() function usage example

 package main

 import (
 "flag"
 "fmt"
 )


 var flagSet *flag.FlagSet

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

 }

 func main() {

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

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




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

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

 // parsing the flags doesn't mean the NFlag count will increase

 // will produce 0
 fmt.Println("BEFORE : Number of flags set :", flagSet.NFlag())


 // set file flag with a value, this will increase the NFlag value by 1
 flagSet.Set("file", "textfile.txt")

 // and by another 1
 flagSet.Set("timeout", "5000")
 flagNum := flagSet.NFlag()

 fmt.Println("AFTER : Number of flags set : ", flagNum)
 }

Output :

Parsed the flag ? : true

BEFORE : Number of flags set : 0

AFTER : Number of flags set : 2

References :

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

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

Advertisement