HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

For loop of two variables in Go

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
variableslooptwofor

Problem

The following for loop in Go isn't allowed,

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.