Command line flags in Golang

Parameters could be passed to console applications in command line, example:

./MyTool -f /home/user -count 20

In this case parameter flags are: -f, and -count, and parameter values are: /home/user and 20

To apply this in Golang we add “flag” to import and write below code:

func main() {
     folder := flag.String("f""/", 
        "Folder name that contents the files")
     count := flag.Int("count"10"Files number to process")
     flag.Parse()
     fmt.Printf("Selected folder: %s, files count: %d\n", 
         *folder, *count) 
}

Example of usage and output:

./MyTool -f /home -count 20
Selected folder: /home, files count: 20

Calling it with –help:

./MyTool --help
Usage of ./MyTool:
-count int
Files number to process (default 10)
-f string
Folder name that contents the files (default "/")

Leave a Reply