Golang subcommands and flags

 

Golang (Go) offers a quick way for your program to accept user flags. You can build a command line interface by using golang’s inbuilt flag package. Using the default options, you can have a few flags up & running with a few lines of code. Here’s an example:

Output:

 

But, what if you want to have sub commands. I ran into this problem while building a tool myself. I needed a bunch of sub commands & then each of the sub command can have different flag options. Here’s what I ended up doing:


We can even go a step further & define your flags as custom types (& not just inbuilt int, string or bool).

I will talk about that in the next post.