gpt4 book ai didi

arrays - Go:循环排序数组,sort.Sort用作值

转载 作者:IT王子 更新时间:2023-10-29 01:54:44 24 4
gpt4 key购买 nike

如何遍历已排序的数组?

我得到了“sort.Sort used as value”错误: 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())
}

}

最佳答案

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())
}

关于arrays - Go:循环排序数组,sort.Sort用作值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40183194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com