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
+9.4k Golang : Terminate-stay-resident or daemonize your program?
+5.7k Linux/Unix/PHP : Restart PHP-FPM
+16.9k Golang : Set up source IP address before making HTTP request
+10.5k Golang : Create matrix with Gonum Matrix package example
+8.6k Android Studio : Import third-party library or package into Gradle Scripts
+4.4k Linux/MacOSX : Search and delete files by extension
+14.5k Golang : Find network of an IP address
+5.5k Clean up Visual Studio For Mac installation failed disk full problem
+16.1k Golang : Generate universally unique identifier(UUID) example
+15.2k Golang : Save(pipe) HTTP response into a file
+9.4k Golang : How to protect your source code from client, hosting company or hacker?
+13.2k Golang : How to calculate the distance between two coordinates using Haversine formula