Next: Declaring Variables, Previous: The for Loop Statement, Up: The First Echo Command using a for Loop [Index]
range OperatorAnother 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
import ("fmt";"os")
func main() {
s, sep := "",""
for _, arg := range os.Args[1:] {
s += sep + arg
sep = " "
}
fmt.Println(s)
}
Listing 1.5: gopl.io/ch1/echo2
In each iteration of the loop, range produces a pair of values:
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 @texinfo:@dfn{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 |
Next: Declaring Variables, Previous: The for Loop Statement, Up: The First Echo Command using a for Loop [Index]