Next: The First Echo Command using a for
Loop, Previous: Some Go Syntax, Up: Tutorial [Index]
os
PackageThe os
package provides functions and other values for dealing with the
operating system in a platform-independent fashion. Command-line arguments are
available to a program in a variable named ‘Args’ that is part of the os
package; thus its name anywhere outside the os package is os.Args
.
The variable os.Args
is a slice of strings. Slices are a
fundamental notion in Go, and we’ll talk a lot more about them soon. For now,
think of a slice as:
s
of array elements where individual elements
can be accessed as s[i]
and a contiguous subsequence as ‘s[m:n]’.
len(s)
.
As in most other programming languages, all indexing in Go uses half-open intervals that include the first index but exclude the last, because it simplifies logic.
s[m:n]
, where ‘0 ≤ m ≤ n ≤ len(s)’, contains n-m
elements.
The first element of os.Args
, os.Args[0]
, is the name of the command
itself.
The other elements are the arguments that were presented to the program
when it started execution. A slice expression of the form s[m:n]
yields a
slice that refers to elements ‘m’ through ‘n-1’, so the elements we need for
our next example are those in the slice os.Args[1:len(os.Args)]
. If ‘m’ or
‘n’ is omitted, it defaults to 0 or len(s)
respectively, so we can abbreviate
the desired slice as os.Args[1:]
.
Next: The First Echo Command using a for
Loop, Previous: Some Go Syntax, Up: Tutorial [Index]