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

标签 types go scope

我收到一条奇怪的错误消息 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

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

最佳答案

这是语言规范。

引用相关部分: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.

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

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

关于types - 范围内的类型重新声明顺序是否应受外部范围的影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32640820/

相关文章:

linux - cgo (for darwin) 的交叉编译失败

arrays - Go:如何在函数中获取 slice 的长度?

c++ - 指针复制到范围外c++

shell - 父子 Shell 脚本问题

haskell - 在 Data.Array.Unboxed 中使用 newtype 和 ghc 7.10

c#检查确切类型

java - 如何将接口(interface)中的 Java 泛型类型参数限制为某些类

inheritance - 如何调用父类(super class)型方法?

go - 如何测试从自定义配置构建的 zap Logger 的日志记录?

delphi - 如何从另一个单元运行程序?