在for循环的初始化器中使用结构体

huangapple go评论66阅读模式
英文:

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 &lt;- 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 &lt;- 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 &#39;{&#39; 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 &lt;- r
}

huangapple
  • 本文由 发表于 2016年2月1日 07:16:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/35120724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定