flag pacakge

The flag package is a built-in library designed to parse those strings into actual variables with specific types. It handles the heavy lifting of validation and formatting.
While in os.args, user has to validate and format the args by himself.

Features

Type Safety: Automatically converts inputs to int, bool, string, etc.
Default values: We can provide default values if the user doesn't provide the flag.
Help Menus: It automatically generates a -help screen based on your code.
Flexibility: It accepts various formats like -name=bob, -name bob, or --name bob.

Parse Command line arguments


package main
import (
        "flag"
        "fmt"
)
func main() {
        // Step-1: Define flags
        //              name,   default_val, "help text"
        port := flag.Int("port", 8080, "Port to listen on")
        debug := flag.Bool("debug", false, "Enable debug mode")

        // Step-2: Parse the command line into the defined flags
        flag.Parse()

        // go run main.go --help
        fmt.Printf("Running on port: %d, debug: %v\n", *port, *debug)
}
        
Example Runs:

$ go run main.go --help
Usage of /tmp/go-build2487568536/b001/exe/main:
  -debug
        Enable debug mode
  -port int
        Port to listen on (default 8080)

$ go run main.go -debug=false -port=90
Running on port: 90, debug: false

$ go run main.go --debug=false --port=90
Running on port: 90, debug: false

$ go run main.go --debug=false
Running on port: 8080, debug: false