构造 for 循环初始化程序 [英] Struct in for loop initializer
问题描述
知道为什么 for 循环初始值设定项中的这个结构表达式会在编译时出现语法错误吗?在这种情况下,指向 struct 的指针工作正常,但我需要像波纹管这样的局部变量.谢谢指教!
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
}
}()
推荐答案
简化代码:
for r := Request{}; r.err == nil; r.id++ {
r.line, r.err = input.ReadSlice(0x0a)
channel <- r
}
给出编译时错误:
预期的布尔值或范围表达式,找到简单的语句(复合文字周围缺少括号?)(还有 1 个错误)
expected boolean or range expression, found simple statement (missing parentheses around composite literal?) (and 1 more errors)
这个结构不利于解析.左大括号 '{'
不明显,它是 复合文字 的一部分还是for
语句本身的左大括号(for
块).
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
}
这篇关于构造 for 循环初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!