Home > Backend Development > Golang > Why Does a Go `for` Loop Fail with a Struct Expression Initializer, and How Can It Be Fixed?

Why Does a Go `for` Loop Fail with a Struct Expression Initializer, and How Can It Be Fixed?

DDD
Release: 2024-12-31 15:20:11
Original
386 people have browsed it

Why Does a Go `for` Loop Fail with a Struct Expression Initializer, and How Can It Be Fixed?

Struct Expression in For Loop Initializer

In Go, using a struct expression as an initializer in a for loop can encounter syntax errors during compilation. While pointers to structs are acceptable, local variables declared through struct expressions may raise issues.

Consider the following code snippet:

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

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 trigger a compile-time error: "expected boolean or range expression, found simple statement (missing parentheses around composite literal?)". The ambiguity arises because the opening brace { can be interpreted as either the beginning of a composite literal or the opening brace of the for block.

To resolve this ambiguity, enclose the struct expression in parentheses, making it clear that it is a composite literal:

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

With this change, the code will compile successfully and execute as intended, initializing the local variable r with a new Request struct and incrementing its id value each iteration.

The above is the detailed content of Why Does a Go `for` Loop Fail with a Struct Expression Initializer, and How Can It Be Fixed?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template