gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:45:37 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com