2

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

// Define Initial Value
i := 0

for {
    // Get random data based on iteration
    data, i := GiveRandomData(i)

    // Save to database
    response, err := SaveToDatabase(data)

    if err != nil { log.Fatal(err) }
    fmt.Println(response)
}

However, when compiling this program, I get the following error:

.\main.go:26: i declared and not used

The Go 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.

What should I do to get rid of this compilation error or to let Go understand that this variable is not unused, but used in the next iteration of this endless for loop?

0

1 Answer 1

9

The Go 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.