In Go, command-line arguments are available in the os.Args
slice.
Here’s an example of how to read command-line arguments in Go:
package main
import (
"fmt"
"os"
)
func main() {
args := os.Args
for i, arg := range args {
fmt.Printf("Argument %d is %s\n", i, arg)
}
}
In this example, the os.Args
slice is assigned to the args
variable. The for
loop iterates over the slice, printing the index and value of each argument. The first argument, os.Args[0]
, is the name of the program being executed, and the rest of the arguments are any additional arguments passed to the program.
Here’s another example that demonstrates how to use command-line flags in Go:
package main
import (
"flag"
"fmt"
)
func main() {
wordPtr := flag.String("word", "default", "a string")
numPtr := flag.Int("num", 42, "an int")
boolPtr := flag.Bool("fork", false, "a bool")
flag.Parse()
fmt.Println("word:", *wordPtr)
fmt.Println("num:", *numPtr)
fmt.Println("fork:", *boolPtr)
fmt.Println("tail:", flag.Args())
}
In this example, the flag
package is used to define command-line flags. The flag.String
, flag.Int
, and flag.Bool
functions are used to define flags of type string, int, and bool respectively. The first argument to these functions is the name of the flag, and the second argument is the default value. The third argument is a help message that will be displayed when the program is run with the -h
or --help
flag.
The flag.Parse
function is then called to parse the command-line arguments. The values of the flags can be accessed using the pointers returned by flag.String
, flag.Int
, and flag.Bool
. The flag.Args
function returns a slice of any arguments that were not associated with a flag.
When run, this program will allow the user to specify values for word
, num
, and fork
flags, and it will print the values of the flags and any remaining arguments.
Leave a Reply