Golang case

实现Sort包,进行切片的排序

package main

import (
    "math/rand"
    "fmt"
    "sort"
)
//定义type 类型是Student的切片
type StudentArray []Student

//定义Student结构体
type Student struct {
    Id   int
    Name string
    Age  int
}

//实现Sort的Len方法
func (p StudentArray) Len() int {
    return len(p)
}

//实现Sort的Less方法
func (p StudentArray) Less(i, j int) bool {
    //倒序或者顺序 只需要改变这里的 < > 即可
    return p[i].Id < p[j].Id
}

//实现Sort的Swap方法
func (p StudentArray) Swap(i, j int) {
    p[i], p[j] = p[j], p[i]
}

func main() {
    var stus StudentArray
    //生成切片
    for i := 0; i < 10; i++ {
        stu := Student{
            Id:   rand.Intn(100),
            Name: fmt.Sprintf("stu%d", rand.Intn(100)),
            Age:  rand.Int(),
        }
        stus = append(stus, stu)
    }
    //调用排序
    sort.Sort(stus)
    //循环输出
    for _,v := range stus{
        fmt.Println(v)
    }
}
{0 stu94 7504504064263669287}
{25 stu40 894385949183117216}
{37 stu6 1874068156324778273}
{47 stu47 6941261091797652072}
{59 stu81 6334824724549167320}
{62 stu89 2933568871211445515}
{66 stu28 7955079406183515637}
{74 stu11 2703387474910584091}
{81 stu87 6129484611666145821}
{88 stu90 6426100070888298971}

关于获取文件的函数

  • path.Base(fullFilename) //获取文件名带后缀
  • path.Ext(filenameWithSuffix) //获取文件后缀
  • strings.TrimSuffix(path.Base(fullFilename), path.Ext(filenameWithSuffix))//获取文件名
fullFilename := "/Users/itfanr/Documents/test.txt"
    fmt.Println("fullFilename =", fullFilename)
    var filenameWithSuffix string
    filenameWithSuffix = path.Base(fullFilename) //获取文件名带后缀
    fmt.Println("filenameWithSuffix =", filenameWithSuffix)
    var fileSuffix string
    fileSuffix = path.Ext(filenameWithSuffix) //获取文件后缀
    fmt.Println("fileSuffix =", fileSuffix)

    var filenameOnly string
    filenameOnly = strings.TrimSuffix(filenameWithSuffix, fileSuffix)//获取文件名
    fmt.Println("filenameOnly =", filenameOnly)