Command-Line Arguments
04/26/21 07:43 Filed in: GO
Today I learn about processing command-line arguments in GO.
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.
When I run this program, I've cleverly called cla.go, I get this:
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.
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.
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.
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.
When I run this program, I've cleverly called cla.go, I get this:
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.
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.
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.