os.arg

The os.Args variable (found in the os package) is a simple slice of strings. It captures everything typed after the program name in the terminal.
How it works?
It indexes every space-separated word.
Index 0: Always the path to the program itself.
The Rest: Any arguments passed by the user.
Example: If you run ./myscript save --force --id=10, os.Args looks like this: ["./myscript", "save", "--force", "--id=10"]
The Downside: To use this, you have to manually write logic to figure out what --force means or convert "10" from a string to an integer.

flag package is better than os.args.

Code


package main
import (
    "fmt"
    "os"
)
func main() {
    fmt.Println ("Number of command line args", len(os.Args))
    for i := 0; i < len(os.Args); i++ {
        fmt.Println ("args[", i, "]", os.Args[i])
    }
}
            

$ go build main.go
$ ./main test tt asa da
Number of command line args 5
args[0]:  ./main
args[ 0 ] ./main
args[ 1 ] test
args[ 2 ] tt
args[ 3 ] asa
args[ 4 ] da