Struct in for loop initializer

2019-01-15 15:04发布

问题:

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
    }
}()

回答1:

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
}