liveBook · Manning

Flag package

As explained in Learn Go with Pocket-Sized Projects

The flag package is a Go standard-library package for parsing command-line flags and converting their values to supported types.

The flag package parses command-line options and converts supplied values into supported Go types, including strings, integers, floating-point numbers, durations, and Booleans. It avoids hand-building syntax and conversion logic around os.Args. section 2.4

A typical flag workflow is:

  • Declare a variable or obtain a pointer with a flag helper such as StringVar or String. section 2.4.1
  • Provide the flag name, default value, and usage description. section 2.4.1
  • Call flag.Parse before reading flag values. section 2.4 section 6.4.1
  • Use flag.Arg to retrieve positional arguments separately from named flags, then validate missing input. section 6.4.1

Language and currency command lines

A greeting program can define -lang with default en, parse it, and pass the result to its greeting logic. A currency converter can define -from and -to, then accept the amount as a positional argument: go run . -from EUR -to CHF 10.50. The -to flag may default to EUR, while a missing amount produces an error and usage output. section 2.4.1 section 6.4.1

Listing 2.17 main.go: Using flags
package main

import (
    "flag"
    "fmt"
)

func main() {
    var lang string 
flag.StringVar(&lang, "lang", "en", "The required language, e.g. en, ur...") #1 flag.Parse() greeting := greet(language(lang)) fmt.Println(greeting) } // language represents a language type language string // phrasebook holds greeting for each supported language var phrasebook = map[language]string{ ... } // greet says hello to the world func greet(l language) string { ... }

Runnable Go code showing StringVar, a default language, flag.Parse, and conversion into a domain-specific language type. section 2.4.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains declaration, defaults, parsing, pointers, and argument retrieval through runnable examples while deferring fuller pointer treatment.
Examples
Uses a language-selecting greeting program and a currency converter with source, target, and amount inputs.
What you can do after
Apply it via Go's flag package to build CLIs that accept typed options, defaults, positional inputs, and missing-input checks.
How it connects
Connects command-line flags with pointers, default values, positional arguments, type conversion, and usage errors.

Also explained in

Compare how 4 books explain flag package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.