patterngoCritical
For loop of two variables in Go
Viewed 0 times
variableslooptwofor
Problem
The following for loop in Go isn't allowed,
What's the correct equivalent of the for-loop of two variables below?
for i := 0, j := 1; i < 10; i++, j++ {...}What's the correct equivalent of the for-loop of two variables below?
for (int i = 0, j = 1; i < 10; i ++ , j ++) {...}Solution
You don't have a comma operator to join multiple statements, but you do have multiple assignment, so this works:
package main
import (
"fmt"
)
func main() {
for i, j := 0, 1; i < 10; i, j = i+1, j+1 {
fmt.Println("Hello, playground")
}
}Code Snippets
package main
import (
"fmt"
)
func main() {
for i, j := 0, 1; i < 10; i, j = i+1, j+1 {
fmt.Println("Hello, playground")
}
}Context
Stack Overflow Q#38081807, score: 251
Revisions (0)
No revisions yet.