Next: Echo3, Previous: Echo1, Up: Command-Line Arguments [Index]
Another form of the for
loop iterates over a range of values from a data
type like a string or a slice. To illustrate, here’s a second version of
echo
:
// Echo2 prints its command-line arguments. package main package main import ( "fmt" "os" ) func main() { s, sep := "", "" for _, arg := range os.Args[1:] { s += sep + arg sep = " " } fmt.Println(s) }
In each iteration of the loop, range
produces a pair of values: the index and
the value of the element at that index. In this example, we don’t need the
index, but the syntax of a range loop requires that if we deal with the
element, we must deal with the index too. One idea would be to assign the
index to an obviously temporary variable like temp
and ignore its value, but
Go does not permit unused local variables, so this would result in a
compilation error.
The solution is to use the blank identifier, whose name is
‘_’ (that is, an underscore). The blank identifier may be used whenever syntax
requires a variable name but program logic does not, for instance to discard an
unwanted loop index when we require only the element value. Most Go
programmers would likely use range
and ‘_’ to write the echo
program as
above, since the indexing over os.Args
is implicit, not explicit, and thus
easier to get right.
This version of the program uses a short variable declaration to declare and
initialize s
and sep
, but we could equally well have declared the variables
separately. There are several ways to declare a string variable; these are all
equivalent:
s := "" var s string var s = "" var s string = ""
Why should you prefer one form to another?
In practice, you should generally use one of the first two forms, with explicit initialization to say that the initial value is important and implicit initialization to say that the initial value doesn’t matter. |
Next: Echo3, Previous: Echo1, Up: Command-Line Arguments [Index]