notexOPENOverview
Notex/Languages/The Complete for Statement
02.06LESSON 06 OF 19 · 1 MIN READ

The Complete for Statement

Always free to read

The first for loop style is the complete for declaration you might be familiar with from C, Java, or JavaScript, as shown in Example 3-8.

Example 3-8. A complete for statement

for i := 0; i < 10; i++ {
    fmt.Println(i)
}

You might be unsurprised to find that this program prints out the numbers from 0 to 9, inclusive.

Just like the if statement, the for statement does not use parentheses around its parts. Otherwise, it should look familiar. The for statement has three parts, separated by semicolons. The first part is an initialization that sets one or more variables before the loop begins. You should remember two important details about the initialization section: First, you must use := to initialize the variables; var is not legal here. Second, just as with variable declarations in if statements, you can shadow a variable here.

Next comes the comparison. This must be an expression that evaluates to a bool. It is checked immediately before each iteration of the loop. If the expression evaluates to true, the loop body is executed.

The last part of a standard for statement is the increment. You usually see something like i{plus}{plus} here, but any assignment is valid. It runs immediately after each iteration of the loop, before the condition is evaluated.

Go allows you to leave out one or more of the three parts of the for statement. Most commonly, you’ll leave off the initialization if it is based on a value calculated before the loop:

i := 0
for ; i < 10; i++ {
    fmt.Println(i)
}

It’s also common to leave off the increment, often because you have a more complicated increment rule inside the loop:

for i := 0; i < 10; {
    fmt.Println(i)
    if i % 2 == 0 {
        i++
    } else {
        i+=2
    }
}
Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K