[Go] Read a command-line flag with the flag package

Created on November 30, 2026

You can use the flag package to define and parse command-line options. This example defines a string flag named name with a default value of Tom.

package main

import (
    "flag"
    "fmt"
)

func main() {
    name := flag.String("name", "Tom", "name to display")
    flag.Parse()
    fmt.Println(*name)
}

flag.String takes the flag name, default value, and help text. After flag.Parse processes the arguments, dereference the pointer returned by flag.String to read the value.

If you save the program as main.go, you can supply a different name.

go run main.go -name Alice
Alice
Go