Golang – 接口编程的最佳实践

func Sort(data Interface)

type Interface interface {
    // Len is the number of elements in the collection.
    Len() int

    // Less reports whether the element with index i
    // must sort before the element with index j.
    //
    // If both Less(i, j) and Less(j, i) are false,
    // then the elements at index i and j are considered equal.
    // Sort may place equal elements in any order in the final result,
    // while Stable preserves the original input order of equal elements.
    //
    // Less must describe a transitive ordering:
    //  - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
    //  - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
    //
    // Note that floating-point comparison (the < operator on float32 or float64 values)
    // is not a transitive ordering when not-a-number (NaN) values are involved.
    // See Float64Slice.Less for a correct implementation for floating-point values.
    Less(i, j int) bool

    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}

实现sort.Sort()

/**
 * @Author: Ne-21
 * @Description: 接口编程的最佳实践
 * @File:  main
 * @Version: 1.0.0
 * @Date: 2022/1/3 15:55
 */

package main

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

// Student 声明一个 Student 结构体
type Student struct {
    Name  string
    Age   int
    Score float64
}

// 声明一个 Student 结构体切片
type stuSlice []Student

// 为 stuSlice 实现 sort 的接口 https://pkg.go.dev/sort#Interface

func (stu stuSlice) Len() int {
    return len(stu)
}
func (stu stuSlice) Less(i, j int) bool {
    // 按score排序
    return stu[i].Score > stu[j].Score
}
func (stu stuSlice) Swap(i, j int) {
    stu[i], stu[j] = stu[j], stu[i]
}

func main() {
    fmt.Println("创建一个stuSlice实例,并向其中加入数据")
    var students stuSlice
    for i := 0; i < 10; i++ {
        student := Student{
            Name:  fmt.Sprintf("学生%d", rand.Intn(100)),
            Age:   rand.Intn(20),
            Score: float64(rand.Intn(100)),
        }
        students = append(students, student)
    }
    fmt.Println("-------------排序前-----------")
    for _, v := range students {
        fmt.Println(v)
    }
    fmt.Println("-------------排序后-----------")
    sort.Sort(students)
    for _, v := range students {
        fmt.Println(v)
    }
}
标题:Golang – 接口编程的最佳实践
作者:Ne-21
文章地址:https://blog.gocos.cn/archives/195.html
转载请注明出处,谢谢!
THE END
分享
二维码
打赏
< <上一篇
下一篇>>