Go by Example: Command-Line Flags
Go by Example : Command-Line Flags
Command-line flags
are a common way to specify options for command-line
programs. For example, in
| |
![]() | |
Go provides a
| |
| |
Basic flag declarations are available for string,
integer, and boolean options. Here we declare a
string flag
| |
This declares
| |
It’s also possible to declare an option that uses an existing var declared elsewhere in the program. Note that we need to pass in a pointer to the flag declaration function. | |
Once all flags are declared, call
| |
Here we’ll just dump out the parsed options and
any trailing positional arguments. Note that we
need to dereference the pointers with e.g.
| |
To experiment with the command-line flags program it’s best to first compile it and then run the resulting binary directly. | |
Try out the built program by first giving it values for all flags. | |
Note that if you omit flags they automatically take their default values. | |
Trailing positional arguments can be provided after any flags. | |
Note that the
| |
Use
| |
If you provide a flag that wasn’t specified to the
| |
Next example: Command-Line Subcommands .
