Struct in for loop initializer

后端 未结 1 922
不知归路
不知归路 2020-11-29 11:28

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

相关标签:
1条回答
  • 2020-11-29 12:25

    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
    }
    
    0 讨论(0)
提交回复
热议问题