Next: , Previous: , Up: Command-Line Arguments   [Index]


1.2.2 Echo2

Range Loop

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)
}

Listing 1.8: gopl.io/ch1/echo2

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 Blank Identifier

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.

Declaring String Variables

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?

  1. The first form, a short variable declaration, is the most compact, but it may be used only within a function, not for package-level variables.
  2. The second form relies on default initialization to the zero value for strings, which is “”.
  3. The third form is rarely used except when declaring multiple variables.
  4. The fourth form is explicit about the variable’s type, which is redundant when it is the same as that of the initial value but necessary in other cases where they are not of the same type.

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]