10

Any idea why this struct expression in for loop initializer makes syntax error in compile-time? Pointer to struct works fine in this case but ofc I need local variable like bellow. Thanks for advices!

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
    }
}()
icza
  • 389,944
  • 63
  • 907
  • 827
bigless
  • 2,849
  • 19
  • 31

1 Answers1

20

Simplifying you code:

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

Gives compile time error:

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

This construct is ambiguous to parse. The opening brace '{' is not obvious whether it is part of a composite literal or the opening brace of the for statement itself (the for block).

You can make it obvious by using parentheses around the composite literal (as the error suggests):

for r := (Request{}); r.err == nil; r.id++ {
    r.line, r.err = input.ReadSlice(0x0a)
    channel <- r
}
icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    Thank you very much! Seems like a Gosublime has different error output..without these suggestions.. – bigless Jan 31 '16 at 23:36
  • 1
    @bigless, (sorry to excavate an old thread but) the output of the compiler may depend on its version: the exact wording of the error messages produced by the toolchain is not covered by the [Go (v1) compatibility guarantees](https://golang.org/doc/go1compat), so it's quite possible that icza merely has a version of Go installed different from that of yours. – kostix Dec 17 '19 at 12:51
  • `go build` doesn't produce that kind of output indeed but `go vet` does. Checked with `go1.17.5`. – bravmi Jan 06 '22 at 09:04