Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access command-line arguments passed to a Go program?

Tags:

go

How do I access command-line arguments in Go? They're not passed as arguments to main.

A complete program, possibly created by linking multiple packages, must have one package called main, with a function

func main() { ... } 

defined. The function main.main() takes no arguments and returns no value.

like image 604
Oleg Razgulyaev Avatar asked Apr 25 '10 06:04

Oleg Razgulyaev


People also ask

How do you access command line arguments passed to a Go program?

Go by Example: Command-Line ArgumentsArgs provides access to raw command-line arguments. Note that the first value in this slice is the path to the program, and os. Args[1:] holds the arguments to the program. You can get individual args with normal indexing.

How do I access command line arguments?

To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments. The value of argc should be non negative. argv(ARGument Vector) is array of character pointers listing all the arguments.

How do I pass a command line argument to a program?

If you want to pass command line arguments then you will have to define the main() function with two arguments. The first argument defines the number of command line arguments and the second argument is the list of command line arguments.


1 Answers

You can access the command-line arguments using the os.Args variable. For example,

package main  import (     "fmt"     "os" )  func main() {     fmt.Println(len(os.Args), os.Args) } 

You can also use the flag package, which implements command-line flag parsing.

like image 125
peterSO Avatar answered Oct 23 '22 13:10

peterSO