Home >Backend Development >Golang >Why Does a Go `for` Loop with a Struct Initializer Cause a Syntax Error?
Struct in for Loop Initializer Syntax Error
In a Go program, using a struct expression as the initializer in a for loop can result in a syntax error at compile time. This error occurs when the opening brace of the struct expression is interpreted ambiguously as the start of the for loop block.
Consider the following code example:
type Request struct { id int line []byte err error } func main() { go func() { for r := Request{}; r.err == nil; r.id++ { r.line, r.err = input.ReadSlice(0x0a) channel <- r } }() }
This code will fail to compile with the error:
expected boolean or range expression, found simple statement (missing parentheses around composite literal?) (and 1 more errors)
To resolve this ambiguity, you can explicitly specify that the struct expression is a composite literal by enclosing it in parentheses:
func main() { go func() { for r := (Request{}); r.err == nil; r.id++ { r.line, r.err = input.ReadSlice(0x0a) channel <- r } }() }
With this modification, the code will compile successfully. The parentheses make it clear that the opening brace is part of a composite literal, not the for loop itself.
The above is the detailed content of Why Does a Go `for` Loop with a Struct Initializer Cause a Syntax Error?. For more information, please follow other related articles on the PHP Chinese website!