2016-10-21 9 views
0

ソートされた配列をループする方法は?Go:ソートされた配列のループ、sort.Sortが値として使用される

私は "sort.Sortが値として使用される" エラーました:場所に 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()) 
    } 

} 

答えて

3

sort.Sort種類を。値を返しません。

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()) 
} 
関連する問題