英文:
Struct in for loop initializer
问题
有没有想法为什么这个在for循环初始化器中的结构表达式会在编译时出现语法错误?在这种情况下,指向结构体的指针可以正常工作,但是我当然需要像下面这样的局部变量。谢谢建议!
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
}
}()
英文:
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
得分: 20
简化你的代码:
for r := Request{}; r.err == nil; r.id++ {
r.line, r.err = input.ReadSlice(0x0a)
channel <- r
}
会产生编译时错误:
预期布尔值或范围表达式,找到简单语句(缺少复合字面量周围的括号?)(还有1个错误)
这个结构在解析时是有歧义的。开括号'{'
不明显是一个复合字面量的一部分,还是for
语句本身(for
块)的开括号。
你可以通过在复合字面量周围使用括号(如错误建议所示)来明确表示:
for r := (Request{}); r.err == nil; r.id++ {
r.line, r.err = input.ReadSlice(0x0a)
channel <- r
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论