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
+11.1k Golang : Web routing/multiplex example
+12.5k Golang : Forwarding a local port to a remote server example
+16.9k Golang : Set up source IP address before making HTTP request
+8.2k Prevent Write failed: Broken pipe problem during ssh session with screen command
+5.4k Golang : Reclaim memory occupied by make() example
+13.2k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+6.9k How to let Facebook Login button redirect to a particular URL ?
+6.2k PHP : Get client IP address
+29.3k Golang : Save map/struct to JSON or XML file
+6.3k Golang : Calculate US Dollar Index (DXY)
+10.2k Golang : How to profile or log time spend on execution?
+9.7k Golang : List available AWS regions