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.
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
Found thread on golang-nuts list talking about this:
Briefly, this is because order of declaration matters inside a function but does not outside. At package scope, the symbols are declared in the order that satisfies their dependencies independent of their appearance on the page; inside a function, they are declared in lexical order. A moment's reflection will show why this inconsistency has merit, although it is, well, inconsistent.
-rob