Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flag command line parsing in golang

Tags:

I'm not sure I understand the reasoning behind this example (taken from here), nor what it is trying to communicate about the Go language:

package main  import (     "flag"     "fmt" )  func main() {     f := flag.NewFlagSet("flag", flag.ExitOnError)     f.Bool("bool", false, "this is bool flag")     f.Int("int", 0, "this is int flag")      visitor := func(a *flag.Flag) {         fmt.Println(">", a.Name, "value=", a.Value)     }      fmt.Println("Visit()")     f.Visit(visitor)     fmt.Println("VisitAll()")     f.VisitAll(visitor)      // set flags     f.Parse([]string{"-bool", "-int", "100"})      fmt.Println("Visit() after Parse()")     f.Visit(visitor)     fmt.Println("VisitAll() after Parse()")     f.VisitAll(visitor) } 

Something along the lines of the setup they have but then adding a

int_val := f.get("int") 

to get the named argument would seem more useful. I'm completely new to Go, so just trying to get acquainted with the language.

like image 882
lollercoaster Avatar asked Nov 04 '13 05:11

lollercoaster


People also ask

How do you use flags in Golang?

Args() method. You can specify the flag by passing the index value i to flag. Args(i) . To run the code, type go build coffee.go first.

What is flag in Go get?

Golang flag package implements command-line flag parsing. Command-line flags are the common way to specify options for command-line programs. We can define flags using flag. String(), flag.

What is the flag in command-line?

Command-line programs often accept flags or options from users to customize the command's execution. Flags are key-value pairs that are added after the command name while running the command.

How do you pass command-line arguments in Golang?

To access all command-line arguments in their raw format, we need to use Args variables imported from the os package . This type of variable is a string ( [] ) slice. Args is an argument that starts with the name of the program in the command-line. The first value in the Args slice is the name of our program, while os.


1 Answers

This is complicated example of using flag package. Typically flags set up this way:

package main  import "flag"  // note, that variables are pointers var strFlag = flag.String("long-string", "", "Description") var boolFlag = flag.Bool("bool", false, "Description of flag")  func init() {     // example with short version for long flag     flag.StringVar(strFlag, "s", "", "Description") }  func main() {     flag.Parse()     println(*strFlag, *boolFlag) }        
like image 124
mechmind Avatar answered Sep 18 '22 06:09

mechmind