Home > Backend Development > Golang > Why Does Using a Struct in a Go For Loop Initializer Cause a Compile-Time Error?

Why Does Using a Struct in a Go For Loop Initializer Cause a Compile-Time Error?

Mary-Kate Olsen
Release: 2024-12-31 06:16:08
Original
1043 people have browsed it

Why Does Using a Struct in a Go For Loop Initializer Cause a Compile-Time Error?

Struct in for Loop Initializer: Composite Literal Ambiguity

In Go, using a struct expression in a for loop initializer can lead to syntax errors if not handled properly. While a pointer to a struct works fine, declaring a local struct variable requires specific syntax.

To illustrate the issue, consider the following code snippet:

type Request struct {
    id   int
    line []byte
    err  error
}

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

This code raises a compile-time error:

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

The ambiguity arises because the opening brace can be interpreted as the start of either a composite literal or the for block. To resolve this, use parentheses around the composite literal:

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

This syntax explicitly declares the composite literal, avoiding the ambiguity during parsing.

The above is the detailed content of Why Does Using a Struct in a Go For Loop Initializer Cause a Compile-Time Error?. 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