for循环初始化器中的结构 [英] Struct in for loop initializer

查看:170
本文介绍了for循环初始化器中的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何想法为什么在for循环初始化的这个struct表达式在编译时会产生语法错误?指向结构的指针在这种情况下工作正常,但是我需要像波纹管这样的局部变量。感谢您的建议!

 类型请求结构{
id int
line [] byte
err错误
}

去func(){
for r:= Request {}; r.err == nil; r.id ++ {
r.line,r.err = input.ReadSlice(0x0a)
channel< - r
}
}()

<$>

对于r:= Request {},p $ p> ; r.err == nil; r.id ++ {
r.line,r.err = input.ReadSlice(0x0a)
channel < - r
>

给出编译时错误:


期望的布尔或范围表达式,找到简单语句(在复合文字周围缺少括号?)(还有1个错误)

这个结构对于解析是不明确的。无论它是否为组合字面值的一部分,大括号'{'>都不明显对于语句本身的开头大括号( for block )。



你可以通过在复合文字周围使用圆括号来明确它(作为错误建议):

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

解决方案

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
}

这篇关于for循环初始化器中的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆