Home > Backend Development > Golang > Why Does a Go `for` Loop with a Struct Initializer Cause a Syntax Error?

Why Does a Go `for` Loop with a Struct Initializer Cause a Syntax Error?

Mary-Kate Olsen
Release: 2024-12-24 01:34:10
Original
1040 people have browsed it

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

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

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

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!

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