golang

Golang Flag

Command-line flags are an important part when building command-line applications. They allow us to modify the behavior of a program. For example, the ls command in Unix allows us to pass flags, such as -l or -a to change the default output.

This article will guide you to create, use, and parse command-line flags using the flags package from the Go standard library.

Required Imports

To use and create flags using the flags package, we need to import them. We can do this using the import clause, as shown below:

import "flags"

Once imported, we can proceed to use it.

Golang Flag Declaration

The flags package allows to perform the flag declaration for string, integer, and Boolean types. This functionality is provided by the flag.String(), flag.Int(), and flag.Bool() methods, respectively.

Let us examine each method closely to understand better how to use them.

Flag.String()

The String method in the flag package allows you to define a string flag with the specified name. The function syntax is as shown:

func String(name string, value string, usage string) *string

The function takes three main arguments: the name of the flag, the default value, and the usage message.

The function then returns an address pointer to the string variable storing the value of the flag.

The following code example shows how to create a string flag:

package main
import (
    "flag"
    "fmt"
)
func main() {
    str := flag.String("username", "root", "Specify login username")
}

In the previous code example, we declare a flag of type string. We set the default value as ““root”” and a short description as the third parameter. The function will return the string pointer.

Flag.Int()

The Int() method is closely similar to the String() method. However, we used this method to declare flags of int type.

An example code is shown below:

int_flag := flag.Int("port", 3006, "specify the port")

Here, we declare an int flag using the Flag.Int() method with a default value of 3006.

Flag.Bool()

To define a Boolean flag, we can use the flag.Bool() method. An example code is provided below:

bool_flag := flag.Bool("exec", true, "Execute command?")

Golang Flag Parsing

Once we have all the flags declared, we use the flag.Parse() method. This will parse the provided flags and allow you to use them:

flag.Parse()

Remember, the flags themselves are pointers and do not hold the actual value. To get the value, we need to dereference with the dereferencing (*) operator.

A source code example is as shown:

package main
import (
    "flag"
    "fmt"
)
func main() {
    str := flag.String("username", "root", "Specify login username")
    int_flag := flag.Int("port", 3006, "specify the port")
    bool_flag := flag.Bool("exec", true, "Execute command?")
    flag.Parse()
    fmt.Println("str: ", *str)
    fmt.Println("int_flag: ", *int_flag)
    fmt.Println("bool_flag: ", *bool_flag)
}

The previous code should return the default value of the specified flags. An example output is provided below:

str:  root
int_flag:  3006
bool_flag:  true

Golang Use Command-Line Flags

To use the flags for the specified program, it is recommended to compile the program and run the program using the resulting binary file.

We can compile a Go program to a binary file using the build command as:

go build <filename.go>

For example, to build the flags program in Go, we can do:

go build flags.go

This should result into an executable file, which you can run from the terminal.

To use the defined flags, we can run the program as:

./flag.exe -username="developer" -port=9000 -exec=true

The previous program should return an output as shown:

str:  developer
int_flag:  9000
bool_flag:  true

To get automatically generated help, we can use the -h flag. An example is as shown:

./flag.exe -h

The previous command should return as:

  -exec
        Execute command? (default true)
  -port int
        specify the port (default 3006)
  -username string
        Specify login username (default "root")

If we specify a flag that isn’t defined in the program, the program returns an error message and displays the help menu.

Example:

./flags.exe -user="user"

The program should return an output as provided below:

$ ./flag.exe -user=user
flag provided but not defined: -user
Usage of /flag.exe:
  -exec
 …. truncated

You can also provide positional arguments after the flags. Ensure that positional arguments come after a flag. Otherwise, Go will treat them as flags.

Conclusion

This was an introductory tutorial on working with command-line flags in the Go programming language. We also discussed the different methods, such as Flag.String(), Flag.Int(), Flag.Bool(), Golang Flag Parsing, Golang Use Command-Line Flags, and Golang Use Command-Line Flags. We hope you found this article helpful. Check out other Linux Hint articles for Go tips and tutorials.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list