Next: , Previous: , Up: The First Echo Command using a for Loop   [Index]


1.5.3 Declaring 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?

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.

As noted above, 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.


Next: The function Join in the strings Package, Previous: Iterate Using the range Operator, Up: The First Echo Command using a for Loop   [Index]