Benjam
Benjam

Reputation: 5326

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

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.

Upvotes: 1

Views: 2495

Answers (1)

Ngenator
Ngenator

Reputation: 11269

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

Upvotes: 7

Related Questions