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

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

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

问题

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

  1. type Thing struct {
  2. Name string
  3. }
  4. type ThingList []Thing

我试图按以下方式遍历ThingList

  1. thingList := GetThingListFilledWithValues()
  2. for _, v := range thingList {
  3. v.DoStuffToThing()
  4. }

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

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

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

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

英文:

I have some structs that are defined as follows:

  1. type Thing struct {
  2. Name string
  3. }
  4. type ThingList []Thing

I am trying to range over ThingList as follows:

  1. thingList := GetThingListFilledWithValues()
  2. for _, v := range thingList {
  3. v.DoStuffToThing()
  4. }

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()函数中返回了错误的内容。

例如:

  1. func GetThingListFilledWithValues() ThingList {
  2. return ThingList{
  3. Thing{Name: "One"},
  4. Thing{Name: "Two"},
  5. }
  6. }

然后可以这样使用:

  1. thingList := GetThingListFilledWithValues()
  2. for _, v := range thingList {
  3. v.DoStuffToThing()
  4. }

这是在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:

  1. func GetThingListFilledWithValues() ThingList {
  2. return ThingList{
  3. Thing{Name: "One"},
  4. Thing{Name: "Two"},
  5. }
  6. }

And use it like so

  1. thingList := GetThingListFilledWithValues()
  2. for _, v := range thingList {
  3. v.DoStuffToThing()
  4. }

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:

确定