Struct in for loop initializer

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
}

Leave a Comment