douluo5937
2016-10-21 18:24
浏览 94
已采纳

Go:循环遍历有序数组sort.Sort用作值

How to loop over sorted array?

I got "sort.Sort used as value" error: https://play.golang.org/p/HP30OyJVrz

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name string
    Age  int
}

func (p Person) String() string {
    return fmt.Sprintf("%s: %d", p.Name, p.Age)
}

// ByAge implements sort.Interface for []Person based on
// the Age field.
type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

func main() {
    people := []Person{
        {"Bob", 31},
        {"John", 42},
        {"Michael", 17},
        {"Jenny", 26},
    }

    fmt.Println(people)
    sort.Sort(ByAge(people))
    fmt.Println(people)

    for _, p := range sort.Sort(ByAge(people)) {
        fmt.Println(p.String())
    }

}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dragon8997474 2016-10-21 18:30
    已采纳

    sort.Sort sorts in place; it doesn't return a value.

    fmt.Println(people)
    sort.Sort(ByAge(people))  // After this, people is already sorted
    fmt.Println(people)
    
    for _, p := range people { // Just range over people if you want
        fmt.Println(p.String())
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题