Next: , Previous: , Up: Tutorial   [Index]


1.4 Working with Command-Line Arguments

os Package

The 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:

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.

Command-line Argument 0—Command name

The first element of os.Args, os.Args[0], is the name of the command itself.

Command-line Arguments 1 through ‘len(os.Args)

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]