dtiopy6088 2015-09-17 22:15
浏览 81
已采纳

范围中的类型重新声明顺序是否应受外部范围影响?

I got a strange error message cannot use []feed literal (type []feed) as type []feed in field value and after some fiddling and minimizing the source I figured out that this situation seems to produce the error:

type user struct {
    Feeds []feed
}
type feed struct{}

func fn() {
    type user struct {
        Feeds []feed // seems to refer to the outer feed type
    }
    type feed struct{}

    _ = user{
        // "cannot use []feed literal (type []feed) as type []feed in field value"
        Feeds: []feed{},
    }
}

http://play.golang.org/p/gNIGhPwAgl

Is this the intended behaviour or a bug? I've spend some time reading the language specification but can't find anything explicitly stating how type declaration order in scopes should work. It's a bit unintuitive that order does not matter in the outer scope but does in the inner.

  • 写回答

2条回答 默认 最新

  • douqi2804 2015-09-17 22:30
    关注

    This is so by the language spec.

    Quoting the relevant part: Declarations and scope:

    The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block.

    Types declared inside a function are only in scope from the type identifier (being declared). Before that they are not.

    type user struct {
        Feeds []feed // This can only be the outer feed type
    }
    
    type feed struct{} // new feed type is in scope from this line
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch