golang_complete_c-style_for

Golang complete, C-style for - Golang Complete for Statement

The Complete for Statement

The first one we’ll look at is the complete for declaration you might be familiar with from C, Java, or JavaScript, as shown in Example 4-8.

Example 4-8. A complete for statement

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

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

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

The second part is the comparison. This must be an expression that evaluates to a bool. It is checked immediately before the loop body runs, after the initialization, and after the loop reaches the end. 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++ here, but any assignment is valid. It runs immediately after each iteration of the loop, before the condition is evaluated.

golang_complete_c-style_for.txt · Last modified: 2025/02/01 06:54 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki