1

I´m having issues implementing the Sort interface in my Go app. Here´s the relevant code:

type Group struct {
   Teams []*Team
}

type Team struct {
    Points int
 }

    type Teams []*Team

            func (slice Teams) Len() int {
                return len(slice)
            }

            func (slice Teams) Less(i, j int) bool {
                return slice[i].Points < slice[j].Points
            }

            func (slice Teams) Swap(i, j int) {
                slice[i], slice[j] = slice[j], slice[i]
            }

So I wanna sort the groups´ teams on based on their points. But whenever I run

sort.Sort(group.Teams)

I get this error:

 cannot use group.Teams (type []*Team) as type sort.Interface in argument
to sort.Sort:   []*Team does not implement sort.Interface (missing Len
method)

Why is this?

1 Answer 1

6

[]*Team is not the same as Teams; you need to explicitly use or cast to the latter:

type Group struct {
   Teams Teams
}
sort.Sort(group.Teams)

Or:

type Group struct {
   Teams []*Team
}
sort.Sort(Teams(group.Teams))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.