In Go, using command-line arguments can be achieved by leveraging the Args variable from the os package. os.Args is a string slice that contains all command-line arguments passed to the program when it is launched. os.Args[0] represents the program name, and os.Args[1:] contains the arguments passed to the program.
Here is a basic example of using command-line arguments:
gopackage main import ( "fmt" "os" ) func main() { // Check the number of command-line arguments if len(os.Args) < 2 { fmt.Println("Please provide at least one argument!") return } // Iterate over all arguments received from the command line for index, arg := range os.Args[1:] { fmt.Printf("Argument %d: %s\n", index+1, arg) } }
Assuming our program is named example, we can run it in the command line as:
shell$ go run example.go arg1 arg2 arg3
The program will output:
shellArgument 1: arg1 Argument 2: arg2 Argument 3: arg3
This program first checks if sufficient command-line arguments are provided (at least one argument is required). Then, it iterates over the os.Args[1:] slice, which excludes the program name and contains only the arguments passed to the program.
This example demonstrates how to receive and process command-line arguments, which is very useful in many command-line applications. For instance, you can modify the program's behavior based on the passed arguments, handle file input/output, or configure the program's settings.