codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐹

Go (Golang)

39 / 72 topics
27Standard Library Overview28IO Package29Net Package30HTTP Package31JSON Package32XML Package33Time Package34OS Package35Fmt Package36Math Package37Regexp Package38Log Package39Flag Package40Context Package41Embed Package
Tutorials/Go (Golang)/Flag Package
🐹Go (Golang)

Flag Package

Updated 2026-04-20
3 min read

Introduction

The flag package in Go is a powerful tool for parsing command-line arguments and flags. It allows developers to easily define, parse, and use command-line options in their applications. This tutorial will provide a comprehensive guide on how to use the flag package effectively, including real-world examples and best practices.

Overview

The flag package provides functions to parse command-line arguments into variables of various types. It supports basic data types like int, float64, string, and boolean values. The package is part of Go's standard library, making it readily available without any additional dependencies.

Key Features

  • Simple API: Easy to define and parse flags.
  • Type Safety: Automatically handles type conversion for flag values.
  • Default Values: Supports setting default values for flags.
  • Help Messages: Generates help messages automatically based on defined flags.

Getting Started

To use the flag package, you need to import it into your Go program. Here's a basic example to illustrate how to define and parse flags:

package main

import (
    "flag"
    "fmt"
)

func main() {
    // Define flags with default values and usage messages
    var name string
    flag.StringVar(&name, "name", "World", "A person's name")

    var age int
    flag.IntVar(&age, "age", 30, "A person's age")

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

    // Use the parsed flags
    fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}

Explanation

  1. Importing the Package: The flag package is imported using import "flag".
  2. Defining Flags:
    • StringVar(&name, "name", "World", "A person's name"): Defines a string flag named name with a default value of "World" and a usage message.
    • IntVar(&age, "age", 30, "A person's age"): Defines an integer flag named age with a default value of 30.
  3. Parsing Flags: flag.Parse() processes the command-line arguments and populates the variables associated with the flags.
  4. Using Flags: After parsing, you can use the values stored in name and age.

Running the Example

To run the above program, save it to a file named main.go and execute it from the terminal:

go run main.go -name=John -age=25

Output:

Hello, John! You are 25 years old.

If you omit the flags, the default values will be used:

go run main.go

Output:

Hello, World! You are 30 years old.

Advanced Usage

Custom Flag Types

The flag package supports defining custom flag types by implementing the Value interface. Here's an example of a custom flag type that parses a comma-separated list of strings:

package main

import (
    "flag"
    "fmt"
    "strings"
)

type StringSlice []string

func (s *StringSlice) String() string {
    return fmt.Sprint(*s)
}

func (s *StringSlice) Set(value string) error {
    *s = strings.Split(value, ",")
    return nil
}

func main() {
    var tags StringSlice
    flag.Var(&tags, "tags", "A comma-separated list of tags")

    flag.Parse()

    fmt.Printf("Tags: %v\n", tags)
}

Explanation

  1. Custom Type: StringSlice is a custom type that implements the Value interface.
  2. String Method: Returns the string representation of the slice.
  3. Set Method: Parses the input string and splits it into a slice of strings.
  4. Using Custom Flag: The flag.Var(&tags, "tags", "A comma-separated list of tags") line defines the custom flag.

Running the Example

go run main.go -tags=tag1,tag2,tag3

Output:

Tags: [tag1 tag2 tag3]

Best Practices

  1. Use Short and Long Flags: Provide both short (-n) and long (--name) flags for better usability.
  2. Default Values: Always set default values to make your program more robust.
  3. Help Messages: Use clear and concise usage messages to guide users on how to use the flags.
  4. Error Handling: Handle errors gracefully, especially when parsing custom flag types.
  5. Testing: Write tests for your command-line applications to ensure they handle various inputs correctly.

Conclusion

The flag package is a versatile tool for handling command-line arguments in Go. By following the guidelines and best practices outlined in this tutorial, you can create powerful and user-friendly command-line applications. Whether you're building simple scripts or complex CLI tools, understanding how to use the flag package effectively will enhance your development experience significantly.

Feel free to explore more advanced features of the flag package, such as handling non-flag arguments with flag.Args() or using flag.Lookup() to access flag values programmatically. Happy coding!


PreviousLog PackageNext Context Package

Recommended Gear

Log PackageContext Package