Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify positional arguments with the flag package in Golang?

Tags:

go

People also ask

How do you use the flag package in Go?

Using the flag package involves three steps: First, define variables to capture flag values, then define the flags your Go application will use, and finally, parse the flags provided to the application upon execution.

How do you use the flag command?

Command-line flags Bool() , flag.Int() , etc. After you've defined your flags, you need to call flag. Parse() . This call will execute command-line parsing and will let you use the flags.

What does flag string do in Golang?

This flag. String function returns a string pointer (not a string value); we'll see how to use this pointer below. This declares numb and fork flags, using a similar approach to the word flag. It's also possible to declare an option that uses an existing var declared elsewhere in the program.

What is command-line flag?

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. Go lets you accept command line flags using the flags package from the standard library.


You just have to check flag.NArg().

From https://golang.org/pkg/flag/#NArg:

NArg is the number of arguments remaining after flags have been processed.

flag.Parse()
if flag.NArg() == 0 { 
    flag.Usage()
    os.Exit(1)
}

You can also use the flag.Narg() function to ensure you have the required number of positional arguments, though I don't know what it gives you over len(flag.Args())

if flag.NArg() < minArgs { 
    // do something
    ...
}