Home >Backend Development >Golang >Why Does Go Throw an Error When Initializing a Struct in a For Loop?
In Go, a syntax error arises when initializing a struct in a for loop. Using a pointer to a struct works fine, but local variables are sometimes necessary. This article delves into the issue and provides a solution.
The problematic code snippet:
for r := Request{}; r.err == nil; r.id++ { r.line, r.err = input.ReadSlice(0x0a) channel <- r }
Simplifying the code, we get:
for r := Request{}; r.err == nil; r.id++ { r.line, r.err = input.ReadSlice(0x0a) channel <- r }
This code results in the following error:
expected boolean or range expression, found simple statement (missing parentheses around composite literal?) (and 1 more errors)
The error stems from the ambiguity in parsing the opening brace ('{'). It could either be part of a composite literal or the start of the for block.
To resolve this ambiguity, parentheses are added around the composite literal:
for r := (Request{}); r.err == nil; r.id++ { r.line, r.err = input.ReadSlice(0x0a) channel <- r }
By enclosing the struct initialization in parentheses, we explicitly indicate that it is a composite literal and not part of the for loop syntax.
The above is the detailed content of Why Does Go Throw an Error When Initializing a Struct in a For Loop?. For more information, please follow other related articles on the PHP Chinese website!