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


1.2.1 Echo1

Here’s an implementation of the Unix echo command, which prints its command-line arguments on a single line. It imports two packages, which are given as a parenthesized list rather than as individual import declarations. Either form is legal, but conventionally the list form is used. The order of imports doesn’t matter; the gofmt tool sorts the package names into alphabetical order.


/* Echo1 prints its command-line arguments. */
package main

import (
        "fmt"
        "os"
)

func main() {
        var s, sep string
        for i := 1; i < len(os.Args); i++ {
                s += sep + os.Args[i]
                sep = " "
        }
        fmt.Println(s)
}

Listing 1.3: gopl.io/ch1/echo1

The echo program could have printed its output in a loop one piece at a time, but this version instead builds up a string by repeatedly appending new text to the end. The string s starts life empty, that is, with value ‘""’, and each trip through the loop adds some text to it; after the first iteration, a space is also inserted so that when the loop is finished, there is one space between each argument. This is a quadratic process that could be costly if the number of arguments is large, but for echo, that’s unlikely. We’ll show a number of improved versions of echo in this chapter and the next that will deal with any real inefficiency.

Comments

Comments begin with ‘//’. All text from a ‘//’ to the end of the line is commentary for programmers and is ignored by the compiler. By convention, we describe each package in a comment immediately preceding its package declaration; for a main package, this comment is one or more complete sentences that describe the program as a whole.

var Declaration and Initialization

The var declaration declares two variables s and sep, of type ‘string’.

Short Variable Declaration

The loop index variable i is declared in the first part of the ‘for’ loop. The ‘:=’ symbol is part of a short variable declaration, a statement that declares one or more variables and gives them appropriate types based on the initializer values.

Arithmetic and Logical Operators—Concatenation Operator

For numbers, Go provides the usual arithmetic and logical operators. When applied to strings, however, the ‘+’ operator concatenates the values, so the expression

sep + os.Args[i]

represents the concatenation of the strings sep and os.Args[i].

Assignment Operators—Assignment Statements

The statement we used in the program,

s += sep + os.Args[i]

is an assignment statement that concatenates the old value of s with sep and os.Args[i] and assigns it back to s; it is equivalent to

s = s + sep + os.Args[i]

The operator ‘+=’ is an assignment operator. Each arithmetic and logical operator like ‘+’ or ‘*’ has a corresponding assignment operator.

Increment and Decrement Statements

The increment statementi++’ adds 1 to i; it’s equivalent to i += 1 which is in turn equivalent to i = i + 1. There’s a corresponding decrement statementi--’ that subtracts 1.

NOTE: These are statements, not expressions as they are in most langauges in the ‘C’ family, j = i++ is illegal and they are postfil only, so ‘--i’ is not legal either.

The for Loop

The for loop is the only loop statement in Go. It has a number of forms, one of which is illustrated here:

for initialization; condition; post {
        // zero or more statements
}

Listing 1.4: For Loop

,*Parentheses* are never used around the three components of a for loop. The ,*braces* are mandatory, however, and the opening brace must be on the same line as the post statement.

initialization statement

The optional initialization statement is executed before the loop starts. If it is present, it must be a simple statement, that is, a short variable declaration, an increment or assignment statement, or a function call.

condition statement

The condition is a boolean expression that is evaluated at the beginning of each iteration of the loop; if it evaluates to ‘true’, the statements controlled by the loop are executed.

post statement

The post statement is executed after the body of the loop, then the condition is evaluated again. The loop ends when the condition becomes false.

Any of these parts may be omitted. If there is no initialization and no post, the semicolons may also be omitted:

// a traditional "while" loop
for condition {
        // ...
}

Listing 1.5: While Loop

If the condition is omitted entirely in any of these forms, for example in

// a traditional infinite loop
for {
        // ...
}

Listing 1.6: Infinite Loop

the loop is infinite, though loops of this form may be terminated in some other way, like a break or return statement.


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