Sling Academy
Home/Golang/Using the `flag` Package for Command-Line Arguments in Go

Using the `flag` Package for Command-Line Arguments in Go

Last updated: November 26, 2024

The flag package in Go provides a simple way to parse command-line arguments. If you're building a Go application that requires input from the user at the command line, the flag package is the way to go.

Importing the Flag Package

To get started, you need to import the flag package. Let's begin with a basic example:

package main

import (
    "flag"
    "fmt"
)

Defining Flags

You can define flags using various functions like flag.String, flag.Int, etc. Here is how you can define a string flag:

var name = flag.String("name", "World", "a name to say hello")

In this example, "name" is the flag's name, "World" is the default value, and "a name to say hello" is some helpful usage information.

Parsing Flags

After defining your flags, use flag.Parse() to parse the command-line arguments:

func main() {
    flag.Parse()
    fmt.Printf("Hello, %s!\n", *name)
}

Once parsed, the value can be retrieved using the pointer returned by the flag definition, in this case, *name.

Example Usage

Here's an example of how this application might be executed from the command line:

$ go run main.go --name=Alice
Hello, Alice!

If the flag is not specified, it defaults to the value "World", as provided in the flag definition:

$ go run main.go
Hello, World!

Defining Other Types of Flags

You can define other types of flags too:

  • Integer flag:
     

    var age = flag.Int("age", 0, "user age")
    
  • Boolean flag:
     

    var debug = flag.Bool("debug", false, "enable debugging")
    

Custom Flag Value Types

For more complex data types, you can implement the flag.Value interface, which consists of Set and String methods.

type Celsius float64

func (c *Celsius) Set(s string) error {
    // parse logic
    return nil
}

func (c *Celsius) String() string {
    return fmt.Sprintf("%v°C", *c)
}

func main() {
    var temp Celsius
    flag.Var(&temp, "temp", "the temperature")
    flag.Parse()
    fmt.Printf("Temperature: %v\n", temp)
}

This guide covers the basics of using the flag package to create and parse command-line flags in Go. With these tools, you can build robust and user-friendly command-line applications.

Next Article: Exploring the `path/filepath` Package for Cross-Platform File Path Handling in Go

Previous Article: Profiling and Debugging Performance with the `pprof` Package in Go

Series: Working with Core package in Go

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