liveBook · Manning

Flag.Parse

As explained in Go in Practice, Second Edition

flag.Parse is a Go flag-package function that parses the defined command-line flags and assigns their values.

flag.Parse parses the defined command-line flags and assigns their values to the variables registered with the flag package. Call it after defining flags, commonly during initialization, before main uses those values. section 2.1.1

Listing 2.2 Hello World using command-line flags
package main

import (
     "flag"      #1
     "fmt"
)

var name = flag.String("name", "World", "A name to say 
hello to.")  #2
var inSpanish bool                                         #3
func init() {

flag.BoolVar(&inSpanish, "spanish", false, "Use 
Spanish language.")

flag.BoolVar(&inSpanish, "s", false, "Use Spanish 
language.")  #4
     flag.Parse()                                        #5
}

func main() {
     if inSpanish {
            fmt.Printf("Hola %s!\n", *name)      #6
     } else {
            fmt.Printf("Hello %s!\n", *name)
     }
}

A complete Go CLI defines string and Boolean flags, calls flag.Parse, and uses the resulting values to choose its output. section 2.1.1

Parsing also determines how invalid, repeated, and incompatible arguments behave:

  • Invalid flags or values trigger an early exit with built-in usage information. section 2.1.1
  • Repeated Boolean aliases are processed in declaration order, so a later value can overwrite an earlier one. section 2.1.1
  • Incompatible types are rejected rather than coerced; time.Duration is an exception with automatic conversion from an integer. section 2.1.1

How Go in Practice, Second Edition covers it

How deep it goes
Explains placement, invalid-input exits, declaration-order overwrites, and type validation, while deferring alternatives to later treatment.
Examples
Uses a Hello World CLI with name, Spanish, shorthand, invalid, and repeated Boolean arguments.
What it assumes
Assumes basic Go CLI structure and flag registration, while demonstrating registration and parsing together.
What you can do after
Operate/configure a Go CLI by registering flags, parsing arguments, and handling built-in validation behavior.
How it connects
Connects flag.Parse with command-line flags, flag.BoolVar, flag.StringVar, default help, and flag.PrintDefaults.

Also explained in

Compare how 2 books explain flag.Parse →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.