Command Line Arguments in Golang
Last Updated :
17 May, 2020
Command-line arguments are a way to provide the parameters or arguments to the main function of a program. Similarly, In Go, we use this technique to pass the arguments at the run time of a program.
In Golang, we have a package called as os package that contains an array called as “Args”. Args is an array of string that contains all the command line arguments passed.
The first argument will be always the program name as shown below.
Example 1: Try to use offline compiler for better results. Save the below file as cmdargs1.go
package main
import (
"fmt"
"os"
)
func main() {
myProgramName := os.Args[0]
fmt.Println(myProgramName)
}
|
Output: Here, you can see it is showing the program name with full path. Basically you can call this as Os Filepath output. If you will run the program with some dummy arguments then that will also print as a program name.
Example 2: Save the below file as cmdargs2.go
package main
import (
"fmt"
"os"
)
func main() {
myProgramName := os.Args[0]
cmdArgs := os.Args[4]
gettingArgs := os.Args[2]
toGetAllArgs := os.Args[1:]
fmt.Println(myProgramName)
fmt.Println(cmdArgs)
fmt.Println(gettingArgs)
fmt.Println(toGetAllArgs)
}
|
Output:
Share your thoughts in the comments
Please Login to comment...