If you’re familiar with command-line interfaces, you might have seen flags like
--name foo, etc. Some of the flags use primitive data types like
bool, etc. The rest of the flags are custom flags that using specific patterns or data structure like
Map, etc. Golang provides a built-in library called
flag to define command-line flags. Some of the provided functions to define flags are straight forward like
flag.Int, etc. But, how about the custom flags? In this article, you will learn some ways to define custom command-line flags in Golang.
Let’s say you want to create a custom flags that accepts a list of string values. The usage of the flag should be like this:
Below are some ways how to define the custom flag.
flag.Var is a way to define a custom flag. It accepts a custom struct that implements
The important thing to note is the
Set method. Everytime your flag is called, the
Set method will be called.
flag.Func is a straight forward way to define a custom flag. It uses
flag.Var under the hood so you don’t need to create a custom struct.
As you see, the last parameter of
flag.Func is a
Set method you implemented in the previous example.
flag.TextVar is a new way introduced in
go1.19. It uses
flag.Var under the hood like
flag.Func, but it accepts a
encoding.TextMarshaler interface instead of
flag.Value interface. It means you can use built-in struct like
time.Time as flags without needed to implement a custom struct.
As you see, it’s similar to
flag.Var but it uses
UnmarshalText instead of
Now you know some ways to define custom command-line flags in Golang. If you want to learn more about
flag package, you can read the official documentation here.
Thank you for reading!