Skip to main content
Command-line flags are a common way to specify options for command-line programs. For example, in wc -l, the -l is a command-line flag. Go provides a flag package supporting basic command-line flag parsing.

Basic Flag Declarations

The flag package provides functions for declaring string, integer, and boolean options:
package main

import (
	"flag"
	"fmt"
)

func main() {

	// Basic flag declarations are available for string,
	// integer, and boolean options. Here we declare a
	// string flag `word` with a default value `"foo"`
	// and a short description. This `flag.String` function
	// returns a string pointer (not a string value);
	// we'll see how to use this pointer below.
	wordPtr := flag.String("word", "foo", "a string")

	// This declares `numb` and `fork` flags, using a
	// similar approach to the `word` flag.
	numbPtr := flag.Int("numb", 42, "an int")
	forkPtr := flag.Bool("fork", false, "a bool")

	// It's also possible to declare an option that uses an
	// existing var declared elsewhere in the program.
	// Note that we need to pass in a pointer to the flag
	// declaration function.
	var svar string
	flag.StringVar(&svar, "svar", "bar", "a string var")

	// Once all flags are declared, call `flag.Parse()`
	// to execute the command-line parsing.
	flag.Parse()

	// Here we'll just dump out the parsed options and
	// any trailing positional arguments. Note that we
	// need to dereference the pointers with e.g. `*wordPtr`
	// to get the actual option values.
	fmt.Println("word:", *wordPtr)
	fmt.Println("numb:", *numbPtr)
	fmt.Println("fork:", *forkPtr)
	fmt.Println("svar:", svar)
	fmt.Println("tail:", flag.Args())
}

Usage Examples

First, compile the program:
go build command-line-flags.go

Providing All Flags

./command-line-flags -word=opt -numb=7 -fork -svar=flag

Using Default Values

If you omit flags, they automatically take their default values:
./command-line-flags -word=opt

Trailing Positional Arguments

Positional arguments can be provided after flags:
./command-line-flags -word=opt a1 a2 a3
The flag package requires all flags to appear before positional arguments. Otherwise, flags will be interpreted as positional arguments.
./command-line-flags -word=opt a1 a2 a3 -numb=7

Built-in Help

The flag package automatically generates help text:
./command-line-flags -h

Flag Types

Pointer Return

flag.String(), flag.Int(), and flag.Bool() return pointers that must be dereferenced with *.

Variable Binding

flag.StringVar(), flag.IntVar(), and flag.BoolVar() bind flags directly to existing variables.
Use the *Var variants (like flag.StringVar()) when you want to bind a flag directly to an existing variable instead of working with pointers.

Next Steps

Command Line Subcommands

Learn how to implement subcommands like go build or git commit

Environment Variables

Explore another way to configure programs using environment variables

Build docs developers (and LLMs) love