117

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 ++) {...} 
3
  • 5
    For reference, all questions like this can be answered in the language spec. For example, you don't even need to scroll or search to find the spec for this, I clicked through For statement->ForClause->SimpleStmt->Assignment
    – JimB
    Jun 28, 2016 at 16:59
  • 7
    Raising the bar for asking qualified questions is great. The upvotes to the answers also show the quality of this very question.
    – sof
    Jun 28, 2016 at 17:15
  • 3
    Possible duplicate of Multiple variables in for loop in Go Dec 30, 2017 at 17:37

4 Answers 4

215

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")
    }
}
2
  • So we can't use something like this i++ or i*=2 in this case? Dec 26, 2020 at 2:34
  • 2
    @princebillyGK Correct. If you're trying to update two variables you're stuck with i, j = expr1, expr2, and increments and *= are statements not expressions.
    – twotwotwo
    Dec 26, 2020 at 21:16
29

Although above Answer is accepted, and it fully satisfy the need. But I would like to contribute some further explanation to it.

Golang Does not support many things which could be done in simple terms. For loop is a most common example of this. The beauty of Go's For loop is that it merges many modern style of looping into one keyword.

Similarly Golang do with Multiple Variable declaration and assignment. According to above mentioned problem, We could solve multi-variable for loop with this simple tool which Golang provides us. If you want to look into further explanation, this question provide further details and way of declaring multiple variables in one statement.

Coming back to for loop, If we want to declare variable of same datatype we can declare them with this

var a,b,c string

but we use short hand in for loop so we can do this for initializing them with same value

  i,j := 0,1

Different Datatypes and Different Values

and if we want to declare different type of variables and want to assign different values we can do this by separating variables names and after := different values by comma as well. for example

 c,i,f,b := 'c',23423,21.3,false

Usage of Assignment Operator

Later on, we can assign values to multiple variables with the same approach.

    x,y := 10.3, 2
    x,y = x+10, y+1

Mixing Struct and Normal types in single statement

Even we can use struct types or pointers the same way. Here is a function to iterate Linked list which is defined as a struct

func (this *MyLinkedList) Get(index int) int {
    for i,list := 0,this; list != nil; i,list = i+1,list.Next{
        if(i==index){
            return list.Val
        }
    }
    return -1
}

This list is defined as

type MyLinkedList struct {
      Val int
      Next *MyLinkedList

 }

Answering to Original Problem

Coming to the origin Question, Simply it could be done

for i, j := 0, 1; i < 10; i, j = i+1, j+1 {
        fmt.Println("i,j",i,j)
    }
5
  • i,j := 0 is wrong: play.golang.org/p/-mAV-unCOp4 assignment mismatch: 2 variables but 1 values
    – Gene S
    Dec 29, 2018 at 19:28
  • its like this for i,j := 0,1; please copy and paste code in playland. you missed second value which is 1 after comma. Dec 29, 2018 at 21:21
  • No, you missed the second value in your answer: "but we use short hand in for loop so we can do this for initializing them with same value i,j := 0"
    – Gene S
    Dec 30, 2018 at 16:50
  • 1
    (I changed the example in the post to match @AbdulRehman's comment because that fixes the syntax error and the comment suggests that was what the example was intended to be.)
    – twotwotwo
    Mar 11, 2019 at 19:25
  • using multiple variables in one line for loop may be less readable. found putting init condition before and post condition inside the loop relatively more readable.
    – Sushil
    Mar 6 at 4:35
2

Suppose you want to loop using two different starting index, you can do this way. This is the example to check if string is palindrome or not.

name := "naman"
for i<len(name) && j>=0{
    if string(name[i]) == string(name[j]){
        i++
        j--
        continue
    }
    return false
}
return true

This way you can have different stopping conditions and conditions will not bloat in one line.

0
-1

As pointed by Mr. Abdul, for iterate among two variable you can use the following construct:

var step int = 4
for row := 0; row < rowMax; row++ {
        for col := 0; col < colMax; col++ {
            for rIndex, cIndex := row, col; rIndex <= row+step && cIndex <= col; rIndex, cIndex = rIndex+1, cIndex+1 {
            }
        }
    }

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.