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


1.2.3 Echo3

Each time around the loop, the string s gets completely new contents. The ‘+=’ statement makes a new string by concatenating the old string, a space character, and the next argument, then assigns the new string to s. The old contents of s are no longer in use, so they will be garbage-collected in due course.

If the amount of data involved is large, this could be costly. A simpler and more efficient solution would be to use the Join function from the strings package:

// Print command-line arguments using strings.Join
package main

import (
        "fmt"
        "os"
        "strings"
)

func main() {
        fmt.Println(strings.Join(os.Args[1:], " "))
}

Listing 1.10: gopl.io/ch1/echo3

Finally, if we don’t care about format but just want to see the values, perhaps for debugging, we can let Println format the results for us:

fmt.Println(os.Args[1:])

The output of this statement is like what we would get from strings.Join, but with surrounding brackets. Any slice may be printed this way.