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 –

<Name>:<Year>:<Stars>:<Recommend>:<Duration>

 

Code:

Output:

Notes:
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.