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
+18k Golang : How to log each HTTP request to your web server?
+5.4k Python : Delay with time.sleep() function example
+9.3k Golang : How to get username from email address
+43.3k Golang : Convert []byte to image
+7.5k Golang : Shuffle strings array
+30.9k error: trying to remove "yum", which is protected
+9.1k Golang : Handle sub domain with Gin
+15.3k Golang : Get query string value on a POST request
+6.4k Golang : Break string into a slice of characters example
+14.2k Golang : Chunk split or divide a string into smaller chunk example
+5.9k Golang : Extract unicode string from another unicode string example
+10.1k Golang : Print how to use flag for your application example