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 :
Advertisement
Something interesting
Tutorials
+7k Golang : Takes a plural word and makes it singular
+10.5k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+10.4k Golang : Meaning of omitempty in struct's field tag
+17.8k Golang : Iterate linked list example
+26.9k Golang : Force your program to run with root permissions
+9.2k Golang : Create and shuffle deck of cards example
+8.8k Golang : Random integer with rand.Seed() within a given range
+5.9k Golang : Detect variable or constant type
+7.7k Golang : Mapping Iban to Dunging alphabets
+10.1k Golang : Print how to use flag for your application example
+13.8k Golang : Gin framework accept query string by post request example
+17.4k Golang : Get future or past hours, minutes or seconds