Sling Academy
Home/Golang/Parsing Command-Line Flags with the `flag` Package in Go

Parsing Command-Line Flags with the `flag` Package in Go

Last updated: November 27, 2024

When building command-line applications in Go, efficiently parsing command-line arguments is crucial. The flag package is a part of Go's standard library that provides a simple way to parse command-line flags. In this article, we will explore how to use the flag package to handle command-line input.

Setting Up Flags

To get started with setting up flags, import the flag package and define variables that store the values of command-line arguments.

package main

import (
    "flag"
    "fmt"
)

func main() {
    // Define a string flag with a default value of "world" and a short description.
    name := flag.String("name", "world", "a name to say hello to")

    // Define an integer flag with a default value of 0 and a short description.
    age := flag.Int("age", 0, "your age")

    // Parse the flag set from the command-line arguments.
    flag.Parse()

    fmt.Printf("Hello, %s! You are %d years old.\n", *name, *age)
}

Running the Code

To build the command-line tool, save the code in a file named main.go and run the following commands:

$ go build main.go
$ ./main --name=Alice --age=30

This should output:

Hello, Alice! You are 30 years old.

Understanding Flags

Flags can be specified in different ways. For example, long options can be written using two dashes like --name=Alice or with a space delimiter such as --name Alice. Short forms can be implemented separately if needed using external packages or custom logic.

Using Different Flag Types

The flag package also provides functions to define other types of flags:

var verbose = flag.Bool("verbose", false, "enable verbose mode")

// You can use other types similar to the following:
var pi = flag.Float64("pi", 3.14, "value of pi")
var help = flag.Bool("help", false, "show help")

Default Values and Help

If you run the program without any arguments, you'll see the output using the default values:

$ ./main
Hello, world! You are 0 years old.

To automatically show usage documentation generated by the flag package, you can use:

flag.Usage()

This prints all the flags available along with their descriptions.

Conclusion

Utilizing the flag package in Go not only simplifies handling command-line arguments but also provides built-in help text generation and type consistency across flags.

Next Article: Working with Dates and Times Using `time` in Go

Previous Article: How to Work with YAML in Go Using `go-yaml`

Series: Go Utilities and Tools

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant