Command-Line Arguments

Today I learn about processing command-line arguments in GO.


Command-Line Arguments



As in many other languages, GO allows users to pass arguments from a shell's command line. This capability is specific to each operating system and is handled by GO's "os" package. The arguments passed into the program are stored in a GO slice (which I learned about last time).

The first thing I'm going to try is pass in some parameters and print them out.

Screen Shot 2021-04-26 at 7.49.15 AM


When I run this program, I've cleverly called cla.go, I get this:

Screen Shot 2021-04-26 at 7.49.35 AM


As in many other programming languages, the first thing returned is the executable program's path. The interesting thing to note are the square brackets around everything. This indicates the parameters are stored in a slice. Also, look at the actual call to os.Arg that returns the slice. There are no parentheses. This is not a function call!

If all I want are the actual parameters I can slice the slice to eliminate the executable.


Screen Shot 2021-04-26 at 7.59.38 AM

Screen Shot 2021-04-26 at 7.59.54 AM

Here, I save the original slice into a variable, all, instead of printing it. I then slice off the first element (the path) with all[1:]. The result as you can see is just another slice with the path removed.

What if I want to iterate over the slice? I can just loop over the slice.

Screen Shot 2021-04-26 at 8.05.02 AM


Screen Shot 2021-04-26 at 8.07.39 AM


I use the underscore in the for statement because I'm not interested in the index of the item that would normally be returned.

That's all there really is to processing command-line arguments in GO.










This site does not track your information.