美文网首页
golang slice 排序

golang slice 排序

作者: 小风吹的我乱了 | 来源:发表于2018-11-13 22:07 被阅读0次

如下示例为,在一个Person切片中,按年龄大小进行排序

package main

import (
    "fmt"
    "sort"
)

/*slice 排序示例*/
type Person struct {
    Age int
}

type PersonSlice []Person

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

func main() {
    persons := PersonSlice{
        Person{
            Age: 1,
        },
        Person{
            Age: 5,
        },
        Person{
            Age: 2,
        },
    }
    sort.Sort(persons)
    fmt.Printf("after sort:%+v", persons)
}

输出 after sort:[{Age:1} {Age:2} {Age:5}]

说明:被排序的结构体需要实现如下接口

type Interface interface {
    // Len is the number of elements in the collection.
    Len() int
    // Less reports whether the element with
    // index i should sort before the element with index j.
    Less(i, j int) bool
    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}

相关文章

  • golang slice 排序

    如下示例为,在一个Person切片中,按年龄大小进行排序 输出 after sort:[{Age:1} {Age:...

  • golang 切片小结

    golang slice

  • golang的排序功能

    golang的排序功能 首先明确两个基础概念 排序基本上针对slice类型 可排序的元数据类型有整数,浮点数,和字...

  • golang slice 简单排序

    sort包中有sort.Slice函数专门用于slice的排序,使用极简单方便 输出 after sort:[1 ...

  • golang sort.Slice

    sort.Slice是golang提供的切片排序方法, 其中使用到了反射(reflect)包 使用了闭包 可以参考...

  • golang slice的误解

    slice的介绍: 在golang的官方文档中,我们发现golang除了有array的数据还有一个slice,而a...

  • Learn Golang in 21 Days - Day 10

    Learn Golang in 21 Days - Day 10 知识点 切片Slice Slice是对数组的抽象...

  • What the official tutorial didn'

    Whoever follow the Golang official tutorial about Slice t...

  • go array 1:2:3 解释

    https://golang.org/ref/spec#Slice_expressions

  • golang

    golang携程调度,runtime包 golang内存模型 csp原理 context的原理 slice底层结构...

网友评论

      本文标题:golang slice 排序

      本文链接:https://www.haomeiwen.com/subject/ymsrfqtx.html