可以对一个只包含[]struct的结构体进行范围遍历吗?

huangapple go评论90阅读模式
英文:

Can I range over a struct that is just a []struct?

问题

我有一些定义如下的结构体:

type Thing struct {
    Name string
}

type ThingList []Thing

我试图按以下方式遍历ThingList

thingList := GetThingListFilledWithValues()
for _, v := range thingList {
    v.DoStuffToThing()
}

它报错说无法遍历thingList,因为它不是一个切片,而是一个type ThingList

在知道它的根是一个切片的情况下,我该如何遍历type ThingList

编辑
所以显然,我在这里的帖子中并不完全正确。我尝试遍历的不是type ThingList,而是type *ThingList,这导致了错误。所以你可以遍历类型为[]StructlistStruct,但不能遍历*listStruct

感谢大家帮助我找到答案。

英文:

I have some structs that are defined as follows:

type Thing struct {
        Name string
}

type ThingList []Thing

I am trying to range over ThingList as follows:

thingList := GetThingListFilledWithValues()
for _, v := range thingList {
        v.DoStuffToThing()
}

It throws an error saying that you can't range over thingList because it's not a slice, but a type ThingList.

How can I range over type ThingList knowing that at it's root, it's a slice?

EDIT:
So apparently, I wasn't fully correct in my post here. Instead of type ThingList being incorrect, it was a type *ThingList that I was trying to range over, which it failed on. So you can range over a listStruct with type []Struct, just not a *listStruct.

Thanks for helping me find the answer, everybody.

答案1

得分: 7

你需要将你的新类型的实例作为函数的返回值。你可能从GetThingListFilledWithValues()函数中返回了错误的内容。

例如:

func GetThingListFilledWithValues() ThingList {
	return ThingList{
		Thing{Name: "One"},
		Thing{Name: "Two"},
	}
}

然后可以这样使用:

thingList := GetThingListFilledWithValues()
for _, v := range thingList {
	v.DoStuffToThing()
}

这是在Go Playground上的完整示例:https://play.golang.org/p/6lGdbBsQgJ

英文:

You need to use an instance of your new type as the return from your function. You must be returning the wrong thing from GetThingListFilledWithValues()

For example:

func GetThingListFilledWithValues() ThingList {
	return ThingList{
		Thing{Name: "One"},
		Thing{Name: "Two"},
	}
}

And use it like so

thingList := GetThingListFilledWithValues()
for _, v := range thingList {
        v.DoStuffToThing()
}

Here's the full example in the go playground https://play.golang.org/p/6lGdbBsQgJ

huangapple
  • 本文由 发表于 2017年1月6日 10:43:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/41498113.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定