BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Flags Package

Go 1.23

Utilize Go's `flag` package to parse command-line flags. This example demonstrates how to define string, integer, and boolean flags, parse them, and access their values, enabling you to build configurable command-line tools.

Code

package main

import (
    "flag"
    "fmt"
)

func main() {
    // Basic flag declarations are available for string, integer, and boolean options.
    wordPtr := flag.String("word", "foo", "a string")

    numbPtr := flag.Int("numb", 42, "an int")
    forkPtr := flag.Bool("fork", false, "a bool")

    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()

    fmt.Println("word:", *wordPtr)
    fmt.Println("numb:", *numbPtr)
    fmt.Println("fork:", *forkPtr)
    fmt.Println("svar:", svar)
    fmt.Println("tail:", flag.Args())
}

Explanation

The standard flag package provides a built-in way to parse command-line options. It supports common types like strings, integers, and booleans, and automatically generates a help message (-h or --help).

Key features:

  • Pointers: Functions like flag.String() return a *pointer* to the value. You must dereference it (e.g., *wordPtr) to use it.
  • Binding: Functions like flag.StringVar() bind a flag to an existing variable, which can be cleaner in some codebases.
  • Syntax: It supports -flag, -flag=value, and -flag value. Note that it uses single dashes by default, unlike the GNU standard double-dash (--flag), though both often work.

Code Breakdown

10
flag.String defines a string flag named "word" with default value "foo" and description "a string". It returns a pointer to a string that will hold the parsed value. Users can set this with -word=value or -word value.
12-13
Defining integer and boolean flags. flag.Int works similarly to flag.String but for integers. flag.Bool is special: it can be set with -fork or -fork=true, and defaults to false if not provided.
15-16
flag.StringVar binds the flag to an existing variable 'svar'. This is useful when you want to avoid working with pointers or when integrating with existing code structures.
19
flag.Parse() must be called after all flags are defined and before accessing their values. This function processes os.Args[1:] and populates the flag variables.
21-24
Accessing the parsed flag values. Note that we dereference the pointers (*wordPtr, *numbPtr, *forkPtr) to get the actual values, while svar is used directly since it's not a pointer.
25
flag.Args() returns any trailing positional arguments that were not parsed as flags. For example, if you run "program -word=hello file1 file2", flag.Args() would return ["file1", "file2"].