Home > Backend Development > Golang > Why Does Go Throw an Error When Initializing a Struct in a For Loop?

Why Does Go Throw an Error When Initializing a Struct in a For Loop?

Barbara Streisand
Release: 2024-12-31 17:48:09
Original
410 people have browsed it

Why Does Go Throw an Error When Initializing a Struct in a For Loop?

Confusion with Struct in For Loop Initializer

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
}
Copy after login
Copy after login

Simplifying the code, we get:

for r := Request{}; r.err == nil; r.id++ {
    r.line, r.err = input.ReadSlice(0x0a)
    channel <- r
}
Copy after login
Copy after login

This code results in the following error:

expected boolean or range expression, found simple statement (missing parentheses around composite literal?) (and 1 more errors)
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template