golang(6): 接口

接口详解

// 举例:sort包中的 Sort 函数,如下:
func Sort(data Interface)
Sort sorts data. It makes one call to data.Len to determine n, and O(n*log(n)) calls to data.Less and data.Swap. The sort is not guaranteed to be stable.
(Sort 对 data 进行排序。 它调用一次 data.Len 来决定排序的长度 n,调用 data.Less 和 data.Swap 的开销为 O(n*log(n))。此排序为不稳定排序。)

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

举例来扩展 Sort 函数的功能,代码如下:

package main

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

type Student struct {
    Name string
    Id string
    Age int
}

type StudentSlice []Student        // 自定义一个切片类型 StudentSlice,切片中的元素是 Student 类型

func (p StudentSlice) Len() int {
    return len(p)
}

func (p StudentSlice) Less(i, j int) bool {
    return p[i].Name < p[j].Name
}

func (p StudentSlice) Swap(i, j int) {
    p[i], p[j] = p[j], p[i]
}

// StudentSlice 类型完全实现了 sort.Sort() 形参中的 Interface 类型,那么 就可以用 sort.Sort() 函数对 StudentSlice 类型的数据进行排序

func main(){
    var stuslice StudentSlice 
    for i := 0; i < 10; i++ {
        stu := Student{        // 生成 Student 类型的结构体
            Name: fmt.Sprintf("stu%d",rand.Intn(100)),
            Id:fmt.Sprintf("110%d",rand.Int()),
            Age: rand.Intn(100),
        }
        stuslice = append(stuslice,stu)        // Student 类型的结构体添加到 stuslice 切片中
    }

    for _, v := range stuslice {
        fmt.Println(v)
    }

    fmt.Println("\n")

    sort.Sort(stuslice)        // 由于stuslice 类型实现了Interface这个接口,那么就能调用 sort.Sort() 对其进行排序

    for _, v := range stuslice {
        fmt.Println(v)
    }
}


// 编译后运行结果如下:
[root@NEO project]# go build -o bin/example01_interface_extend go_dev/day06/example01_interface_extend/main
[root@NEO project]# bin/example01_interface_extend 
{stu81 1108674665223082153551 47}
{stu59 1103916589616287113937 18}
{stu25 1101443635317331776148 56}
{stu0 1104751997750760398084 11}
{stu62 1103510942875414458836 28}
{stu74 1102610529275472644968 45}
{stu37 1102015796113853353331 95}
{stu66 1105263531936693774911 58}
{stu47 1102740103009342231109 87}
{stu88 1107981306761429961588 15}


{stu0 1104751997750760398084 11}
{stu25 1101443635317331776148 56}
{stu37 1102015796113853353331 95}
{stu47 1102740103009342231109 87}
{stu59 1103916589616287113937 18}
{stu62 1103510942875414458836 28}
{stu66 1105263531936693774911 58}
{stu74 1102610529275472644968 45}
{stu81 1108674665223082153551 47}
{stu88 1107981306761429961588 15}
[root@NEO project]# 

// 任何类型,只要实现了它的规范(接口),就可以调用它的函数来排序

猜你喜欢

转载自www.cnblogs.com/neozheng/p/11273687.html