我有一些结构定义如下:
type Thing struct {
Name string
}
type ThingList []Thing
Run Code Online (Sandbox Code Playgroud)
我想尝试的范围ThingList如下:
thingList := GetThingListFilledWithValues()
for _, v := range thingList {
v.DoStuffToThing()
}
Run Code Online (Sandbox Code Playgroud)
它会抛出一个错误,说你不能超出范围,thingList因为它不是切片,而是a type ThingList.
我怎么能type ThingList知道它的根部是一片呢?
编辑:显然,我在这里的帖子中并不完全正确.而不是type ThingList不正确,这是type *ThingList我试图超越,它失败了.因此,您可以使用类型覆盖listStruct []Struct,而不是a *listStruct.
感谢大家帮我找到答案.
您需要使用新类型的实例作为函数的返回值.你必须从错误的东西回来GetThingListFilledWithValues()
例如:
func GetThingListFilledWithValues() ThingList {
return ThingList{
Thing{Name: "One"},
Thing{Name: "Two"},
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它
thingList := GetThingListFilledWithValues()
for _, v := range thingList {
v.DoStuffToThing()
}
Run Code Online (Sandbox Code Playgroud)
以下是go playground中的完整示例https://play.golang.org/p/6lGdbBsQgJ
| 归档时间: |
|
| 查看次数: |
1252 次 |
| 最近记录: |