Go Flags – Part 2

In my earlier posts – Go subcommands and flags – I talked about defining Go flags & how to implement subcommands in Go & define flags for those subcommands.

In this post, let’s take it a step further & understand how to define flags based on any type – and not just int or string or bool. We can define user flags based on any complex type. Go’s flag package defines/exposes interface to do just that. package flag has an interface flag.Value


In the previous post, we created an example of an imaginative tool – netflix – and defined 2 subcommands – create & delete with flags like name of the movie, year it was released and so on.

Let’s now define a new flag – movie, that is a an aggregate type – of the format –





Basically the movieFlag type satisfied the interface flag.Value by defining 2 methods – String & Set. And then using the function flag.CommandLine.Var, it initialized a flag variable of the type movieFlag.

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:



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.