In Go, you can use the flag
package to define and parse command-line arguments, both positional and flag arguments. However, the flag
package is more focused on flag-style arguments, where you specify the argument name followed by a value using a flag syntax (-name value
or --name value
).
For positional (non-flag) command-line arguments, you can use the os
package to access the command-line arguments directly. Here's an example of how you can define and parse positional arguments in Go:
package main
import (
"fmt"
"os"
)
func main() {
args := os.Args[1:] // Skip the program name (first argument)
// Check if the expected number of arguments is provided
if len(args) != 3 {
fmt.Println("Usage: program <arg1> <arg2> <arg3>")
return
}
arg1 := args[0]
arg2 := args[1]
arg3 := args[2]
// Use the parsed arguments as needed
fmt.Printf("arg1: %s\n", arg1)
fmt.Printf("arg2: %s\n", arg2)
fmt.Printf("arg3: %s\n", arg3)
}
In this example, we use os.Args
to access the command-line arguments. We skip the first argument (program name) using os.Args[1:]
, and then check if the expected number of arguments is provided. If not, we print a usage message and exit.
Assuming the program is compiled and named program
, you can run it like this:
$ go run main.go value1 value2 value3
This will output:
arg1: value1
arg2: value2
arg3: value3
Make sure to replace value1
, value2
, value3
with your desired arguments.