参考文章https://studygolang.com/articles/2652
-
接口 interface
interface 类型可以定义一组方法,但是这些不需要实现,并且interface不能包含任何的变量 提供了规范 类似于c++里面的虚函数。 -
定义方法
//接口
type example interface{
//方法
method1(参数列表) 返回值列表
method2(参数列表)返回值列表
}
An interface type specifies a method set called its interface.
A variable of interface type can store a value of any type with a method set that is any superset of the interface.
Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.
Go 语言提供了另外一种数据类型即接口(interface),它把所有的具有共性的方法定义在一起,这些方法只有函数签名,没有具体的实现代码(类似于Java中的抽象函数),任何其他类型只要实现了接口中定义好的这些方法,那么就说 这个类型实现(implement)了这个接口
示例:sort接口当中有三个方法 Swap Less Len StudentArray这个类型实现了这三个方法,就相当于实现了sort接口
package main
import(
"fmt"
"math/rand"
"sort"
)
type Student struct{
Name string
Id string
Age int
}
type StudentArray []Student
func (p StudentArray) Len() int{
return len(p)
}
func (p StudentArray) Less(i, j int) bool{
return p[i].Name >p[j].Name
}
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{
Name:fmt.Sprintf("stu%d",rand.Intn(100)),
Id:fmt.Sprintf("%d",rand.Int()),
Age: rand.Intn(100),
}
stus = append(stus,stu)
}
for _,v := range stus{
fmt.Println(v)
}
sort.Sort(stus)
fmt.Println()
fmt.Println()
for _,v := range stus{
fmt.Println(v)
}
}