Four Ways of Writing Go Iteration
Iteration in programming referring to the action that is keep repeating of an instruction, and often known as Loop. In Go programming language, there is no while or do-while statement, they are all unified as for statement.
Go Iteration
Iteration in programming referring to the action that is keep repeating of an instruction, and known as Loop.
For statement
In Go programming language, there is no while
or do-while
statement, they are all unified as for
statement.
There are three ways to write a for
statement.
// With init, condition and post
for i := 0; i < 10; i++ {
sum += i
}
// Only condition
b := true
for b {
b = false
}
// for without a condition
for {
break
}
Range statement
Range
is similar like foreach
loop in a way.
Below is the clause from the The Go Programming Language Specification for the For Statement
A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.
Loop for a index and value
for index, value := range m {
}
Loop for a key and value
for k, v := range m {
}
Loop for the first item
for k := range m {
}
Loop for the second item
for _, v := range m {
}
Caveats
According to the Effective Go documentation, for
statement in Go has no,
-
comma operator and
-
++
and--
are statements not expressions
Below is the clause from the The Go Programming Language Specification for the For Statement
Finally, Go has no comma operator and ++ and -- are statements not expressions. Thus if you want to run multiple variables in a for you should use parallel assignment (although that precludes ++ and --).
Hence, multiple variables should be used in a for
statement.
for i < 10 {
// Syntax error: unexpected ++ at end of statement
sum = j++
// Syntax error: unexpected ++, expecting expression
sum = ++j
// Valid Expression
sum += j
}
However that precludes ++
and --