Command Line Arguments in Golang

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show how
// to use command-line arguments
package main
  
import (
    "fmt"
    "os"
)
  
func main() {
  
    // The first argument
    // is always program name
    myProgramName := os.Args[0]
      
    // it will display 
    // the program name
    fmt.Println(myProgramName)
}

chevron_right


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.



Command-Line-Arguments-Golang

Example 2: Save the below file as cmdargs2.go

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to show how
// to use command-line arguments
package main
  
import (
    "fmt"
    "os"
)
  
func main() {
  
    // The first argument
    // is always program name
    myProgramName := os.Args[0]
  
    // this will take 4
    // command line arguments
    cmdArgs := os.Args[4]
  
    // getting the arguments
    // with normal indexing
    gettingArgs := os.Args[2]
  
    toGetAllArgs := os.Args[1:]
  
    // it will display
    // the program name
    fmt.Println(myProgramName)
      
    fmt.Println(cmdArgs)
      
    fmt.Println(gettingArgs)
      
    fmt.Println(toGetAllArgs)
}

chevron_right


Output:

Command-Line-Arguments-Go-Programming-Langauge




My Personal Notes arrow_drop_up

Young professional who is passionate and dedicated about what she do and does not hesitate to go an extra mile to explore herself more as a professional Prerna holds merit in addition with two technical International

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.