其他分享
首页 > 其他分享> > Go: Custom Sort

Go: Custom Sort

作者:互联网

package main

import (
    "fmt"
    "math/rand"
    "sort"
    "time"
)

// Vale Vale结构体
type Vale struct {
    Name string
    Age  int
}

func (vale Vale) String() string {
    return fmt.Sprintf("Name=%v, Age=%v", vale.Name, vale.Age)
}

// ValeSlice Vale的切片
type ValeSlice []Vale

func (valeSlice ValeSlice) Len() int {
    return len(valeSlice)
}
func (valeSlice ValeSlice) Less(i, j int) bool {
    // return valeSlice[i].Age < valeSlice[j].Age  // Age  Ascend
    return len(valeSlice[i].Name) > len(valeSlice[j].Name)
}
func (valeSlice ValeSlice) Swap(i, j int) {
    /*  tmp := valeSlice[i]
        valeSlice[i] = valeSlice[j]
        valeSlice[j] = tmp*/
    valeSlice[i], valeSlice[j] = valeSlice[j], valeSlice[i]
}
func main() {
    var intSlice = []int{7, 5, -5, 0, 3}
    sort.Ints(intSlice)
    fmt.Println(intSlice)

    rand.Seed(time.Now().Unix())

    var valeSlice ValeSlice
    for i := 0; i < 10; i++ {
        intn := rand.Intn(100)
        vale := Vale{
            Name: fmt.Sprintf("vale-%d", intn),
            Age:  intn,
        }
        valeSlice = append(valeSlice, vale)
    }
    for _, v := range valeSlice {
        fmt.Println(v)
    }

    sort.Sort(valeSlice)

    fmt.Println("~~~~~After Sort~~~~~")
    for _, v := range valeSlice {
        fmt.Println(v)
    }
}

 

 

标签:Sort,Name,fmt,Vale,Custom,Age,vale,Go,valeSlice
来源: https://www.cnblogs.com/dissipate/p/16285825.html