【问题标题】:Should type redeclare order in a scope be effected by outer scope?范围内的类型重新声明顺序是否应该受外部范围的影响?
【发布时间】:2015-12-14 22:36:30
【问题描述】:

我收到一条奇怪的错误消息 cannot use []feed literal (type []feed) as type []feed in field value,经过一番摆弄和最小化源代码后,我发现这种情况似乎会产生错误:

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

这是预期的行为还是错误?我花了一些时间阅读语言规范,但找不到任何明确说明作用域中的类型声明顺序应该如何工作的内容。顺序在外部范围内无关紧要,但在内部范围内有关系,这有点不直观。

【问题讨论】:

  • 投了反对票。不知道这个问题有什么问题。似乎甚至该语言的一位作者也认为这有点不一致,但有充分的理由。

标签: types go scope


【解决方案1】:

语言规范是这样的。

引用相关部分:Declarations and scope:

在函数中声明的类型标识符的范围从 TypeSpec 中的标识符开始,到最里面的包含块的末尾结束。

在函数内声明的类型仅在类型标识符(被声明的)范围内。在此之前,他们不是。

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

【讨论】:

  • 谢谢。我想这或多或少是 rob 的回答,但以更正式的方式:)
【解决方案2】:

发现thread on golang-nuts list在谈论这个:

简而言之,这是因为声明的顺序在函数内部很重要,但在外部不重要。在包范围内,符号按照满足其依赖关系的顺序声明,与它们在页面上的外观无关;在函数内部,它们按词法顺序声明。片刻的反思将说明为什么这种不一致有优点,尽管它是,嗯,不一致。
-抢劫

【讨论】:

    猜你喜欢
    • 2017-12-02
    • 2022-08-04
    • 2013-01-18
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多