Retrieving Command-Line Arguments in Go Programs
In Go, command-line arguments are not directly passed as parameters to the main function. To access them, the os.Args variable provides a slice of strings representing the arguments passed to the program.
Accessing Arguments with os.Args
The os.Args variable is available within the main function and holds the following information:
Example:
package main import ( "fmt" "os" ) func main() { fmt.Println("Program name:", os.Args[0]) fmt.Println("Arguments:", os.Args[1:]) }
This program prints the name of the program and the command-line arguments passed to it.
Using the flag Package
Go also provides the flag package, which simplifies command-line argument parsing. The flag package allows you to define and parse flags, which are named parameters that can be set when the program is invoked.
Example:
package main import ( "flag" "fmt" ) var name string func init() { flag.StringVar(&name, "name", "Default name", "Set the program's name") } func main() { flag.Parse() fmt.Println("Hello", name) }
In this example, the -name flag can be used to specify a name. The flag is parsed and assigned to the name variable in the init function.
The above is the detailed content of How Do I Retrieve and Use Command-Line Arguments in Go?. For more information, please follow other related articles on the PHP Chinese website!