use of variable in for loop not recognized in Golang

后端 未结 1 1090
夕颜
夕颜 2021-01-21 11:24

I\'m developing in golang and I run the following for loop:

// Define Initial Value
i := 0

for {   
    // Get Random data based on iteration
    data, i := Giv         


        
相关标签:
1条回答
  • 2021-01-21 12:29

    The Golang compiler doesn't seem to recognise that the i variable is given back to the function in the next loop. Inside this function, the I variable changes value.

    No, i does not change value; := declares a new i. (Go allows you to do this because data is also new.) To assign to it instead, you’ll need to declare data separately:

    var data RandomDataType
    data, i = GiveRandomData(i)
    

    Or give the new i a temporary name:

    data, next := GiveRandomData(i)
    i = next
    
    0 讨论(0)
提交回复
热议问题