Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Parse Command Line Arguments Using Flag in Go

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

It is suggested that you use the Golang module spf13/cobra (instead of the standard Golang library flag) for parsing command-line arguments.

Declare a string flag --name with a default value “Ben” and a short description. Notice that the function flag.String returns a string pointer (not a string value).

Ben
42
false
[/home/dclong/.local/share/jupyter/runtime/kernel-9d64ca68-de95-4d2c-a5a1-256edc785832.json]

Sub Commands

You can define sub-commands using flag.NewFlagSet. However, flag does not automatically generate help docs for sub-commands defined (which is not as convenient as argparse in Python). One way to improve the default behavior here is to overwrite the -h option for the main command and print help documentation on sub-commands when -h is specified. Below is such an example.